Files
paseo/packages/react-native-enriched-markdown/ios/internals/MeasurementCache.h
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

304 lines
11 KiB
C++

#pragma once
#include <CoreGraphics/CGBase.h>
#include <React/RCTUtils.h>
#include <list>
#include <mutex>
#include <react/renderer/graphics/Float.h>
#include <string>
#include <tuple>
#include <unordered_map>
namespace facebook::react {
struct HashUtils {
static inline size_t combine(size_t h, size_t v)
{
return h ^ (v + 0x9e3779b97f4a7c15ULL + (h << 6) + (h >> 2));
}
template <typename T> static inline void hash_one(size_t &seed, const T &v)
{
seed = combine(seed, std::hash<T>{}(v));
}
};
enum class MarkdownFlavor : uint8_t {
CommonMark = 0,
GitHub = 1,
};
struct MeasurementCacheKey {
std::string markdown;
CGFloat maxWidth;
bool allowTrailingMargin;
bool allowFontScaling;
double maxFontSizeMultiplier;
bool md4cFlagsUnderline;
bool md4cFlagsSuperscript;
bool md4cFlagsSubscript;
bool md4cFlagsHighlight;
bool md4cFlagsLatexMath;
bool md4cFlagsHardSoftBreaks;
bool md4cFlagsPreserveBlankLines;
bool md4cFlagsAdmonitions;
size_t styleFingerprint;
size_t linkPillContentFingerprint;
CGFloat fontScale;
MarkdownFlavor flavor;
std::string lineBreakStrategyIOS;
std::string writingDirection;
int numberOfLines;
std::string ellipsizeMode;
std::string linkRegexKey;
std::string inlineCodeLinkRegexKey;
bool operator==(const MeasurementCacheKey &other) const
{
return std::tie(markdown, maxWidth, allowTrailingMargin, allowFontScaling, maxFontSizeMultiplier,
md4cFlagsUnderline, md4cFlagsSuperscript, md4cFlagsSubscript, md4cFlagsHighlight,
md4cFlagsLatexMath, md4cFlagsHardSoftBreaks, md4cFlagsPreserveBlankLines, md4cFlagsAdmonitions,
styleFingerprint, linkPillContentFingerprint, fontScale, flavor, lineBreakStrategyIOS,
writingDirection, numberOfLines, ellipsizeMode, linkRegexKey, inlineCodeLinkRegexKey) ==
std::tie(other.markdown, other.maxWidth, other.allowTrailingMargin, other.allowFontScaling,
other.maxFontSizeMultiplier, other.md4cFlagsUnderline, other.md4cFlagsSuperscript,
other.md4cFlagsSubscript, other.md4cFlagsHighlight, other.md4cFlagsLatexMath,
other.md4cFlagsHardSoftBreaks, other.md4cFlagsPreserveBlankLines, other.md4cFlagsAdmonitions,
other.styleFingerprint, other.linkPillContentFingerprint, other.fontScale, other.flavor,
other.lineBreakStrategyIOS, other.writingDirection, other.numberOfLines, other.ellipsizeMode,
other.linkRegexKey, other.inlineCodeLinkRegexKey);
}
};
struct MeasurementCacheKeyHash {
size_t operator()(const MeasurementCacheKey &key) const
{
size_t h = 0;
HashUtils::hash_one(h, key.markdown);
HashUtils::hash_one(h, key.maxWidth);
HashUtils::hash_one(h, key.allowTrailingMargin);
HashUtils::hash_one(h, key.allowFontScaling);
HashUtils::hash_one(h, key.maxFontSizeMultiplier);
HashUtils::hash_one(h, key.md4cFlagsUnderline);
HashUtils::hash_one(h, key.md4cFlagsSuperscript);
HashUtils::hash_one(h, key.md4cFlagsSubscript);
HashUtils::hash_one(h, key.md4cFlagsHighlight);
HashUtils::hash_one(h, key.md4cFlagsLatexMath);
HashUtils::hash_one(h, key.md4cFlagsHardSoftBreaks);
HashUtils::hash_one(h, key.md4cFlagsPreserveBlankLines);
HashUtils::hash_one(h, key.md4cFlagsAdmonitions);
HashUtils::hash_one(h, key.styleFingerprint);
HashUtils::hash_one(h, key.linkPillContentFingerprint);
HashUtils::hash_one(h, key.fontScale);
HashUtils::hash_one(h, static_cast<uint8_t>(key.flavor));
HashUtils::hash_one(h, key.lineBreakStrategyIOS);
HashUtils::hash_one(h, key.writingDirection);
HashUtils::hash_one(h, key.numberOfLines);
HashUtils::hash_one(h, key.ellipsizeMode);
HashUtils::hash_one(h, key.linkRegexKey);
HashUtils::hash_one(h, key.inlineCodeLinkRegexKey);
return h;
}
};
struct CachedSize {
CGFloat width;
CGFloat height;
};
template <typename StyleStruct> inline size_t computeStyleFingerprint(const StyleStruct &s)
{
size_t h = 0;
auto hashFields = [&](auto... args) { (HashUtils::hash_one(h, args), ...); };
auto hashTextLayout = [&](const auto &item) {
hashFields(item.fontFamily, item.fontSize, item.fontWeight, item.marginTop, item.marginBottom, item.lineHeight);
};
// Block Elements
hashTextLayout(s.paragraph);
hashFields(s.paragraph.textAlign);
hashTextLayout(s.h1);
hashFields(s.h1.textAlign);
hashTextLayout(s.h2);
hashFields(s.h2.textAlign);
hashTextLayout(s.h3);
hashFields(s.h3.textAlign);
hashTextLayout(s.h4);
hashFields(s.h4.textAlign);
hashTextLayout(s.h5);
hashFields(s.h5.textAlign);
hashTextLayout(s.h6);
hashFields(s.h6.textAlign);
hashTextLayout(s.blockquote);
hashFields(s.blockquote.borderWidth, s.blockquote.gapWidth, s.blockquote.padding, s.blockquote.borderRadius);
hashTextLayout(s.list);
hashFields(s.list.bulletSize, s.list.markerMinWidth, s.list.markerFontWeight, s.list.gapWidth, s.list.marginLeft,
s.list.itemSpacing);
// Code & Inlines
hashFields(s.codeBlock.fontFamily, s.codeBlock.fontSize, s.codeBlock.fontWeight, s.codeBlock.marginTop,
s.codeBlock.marginBottom, s.codeBlock.lineHeight, s.codeBlock.padding, s.codeBlock.borderRadius,
s.codeBlock.borderWidth);
hashFields(s.code.fontFamily, s.code.fontSize, s.code.fontScale);
hashFields(s.link.fontFamily, s.strong.fontFamily, s.strong.fontWeight, s.em.fontFamily, s.em.fontStyle);
// Variants change link metrics: a font family, or a pill box around the label.
for (const auto &variant : s.linkVariants) {
hashFields(variant.pattern, variant.fontFamily, variant.pill.enabled, variant.pill.label, variant.pill.iconUri,
variant.pill.paddingHorizontal, variant.pill.paddingVertical, variant.pill.lineHeight,
variant.pill.borderWidth, variant.pill.maxWidth);
}
hashFields(s.highlight.backgroundColor, s.highlight.color);
// Visual/Spacing Elements
hashFields(s.image.height, s.image.maxHeight, s.image.aspectRatio, s.image.marginTop, s.image.marginBottom);
hashFields(s.video.marginTop, s.video.marginBottom, s.video.borderRadius, s.video.aspectRatio,
s.video.backgroundColor);
hashFields(s.inlineImage.size);
hashFields(s.thematicBreak.height, s.thematicBreak.marginTop, s.thematicBreak.marginBottom);
// Complex Components
hashTextLayout(s.table);
hashFields(s.table.headerFontFamily, s.table.cellPaddingHorizontal, s.table.cellPaddingVertical, s.table.borderWidth,
s.table.borderRadius, s.table.horizontalOverflow);
hashFields(s.math.fontSize, s.math.padding, s.math.marginTop, s.math.marginBottom, s.math.textAlign);
hashFields(s.taskList.checkboxSize, s.taskList.checkboxBorderRadius);
return h;
}
// Pill labels and icons (the `linkPillContent` prop) change link widths.
template <typename ContentVector> inline size_t computeLinkPillContentFingerprint(const ContentVector &content)
{
size_t h = 0;
for (const auto &entry : content) {
HashUtils::hash_one(h, entry.url);
HashUtils::hash_one(h, entry.label);
HashUtils::hash_one(h, entry.iconUri);
}
return h;
}
template <typename RegexProps> inline std::string buildLinkRecognitionCacheKey(const RegexProps &props)
{
std::string key;
key += props.caseInsensitive ? '1' : '0';
key += props.dotAll ? '1' : '0';
key += props.isDisabled ? '1' : '0';
key += props.isDefault ? '1' : '0';
return key + props.pattern;
}
template <typename PropsType>
inline MeasurementCacheKey buildMeasurementCacheKey(const PropsType &props, CGFloat maxWidth, CGFloat fontScale,
MarkdownFlavor flavor)
{
return MeasurementCacheKey{
.markdown = props.markdown,
.maxWidth = maxWidth,
.allowTrailingMargin = props.allowTrailingMargin,
.allowFontScaling = props.allowFontScaling,
.maxFontSizeMultiplier = props.maxFontSizeMultiplier,
.md4cFlagsUnderline = props.md4cFlags.underline,
.md4cFlagsSuperscript = props.md4cFlags.superscript,
.md4cFlagsSubscript = props.md4cFlags.subscript,
.md4cFlagsHighlight = props.md4cFlags.highlight,
.md4cFlagsLatexMath = props.md4cFlags.latexMath,
.md4cFlagsHardSoftBreaks = props.md4cFlags.hardSoftBreaks,
.md4cFlagsPreserveBlankLines = props.md4cFlags.preserveBlankLines,
.md4cFlagsAdmonitions = props.md4cFlags.admonitions,
.styleFingerprint = computeStyleFingerprint(props.markdownStyle),
.linkPillContentFingerprint = computeLinkPillContentFingerprint(props.linkPillContent),
.fontScale = fontScale,
.flavor = flavor,
.lineBreakStrategyIOS = props.lineBreakStrategyIOS,
.writingDirection = props.writingDirection,
.numberOfLines = props.numberOfLines,
.ellipsizeMode = props.ellipsizeMode,
.linkRegexKey = buildLinkRecognitionCacheKey(props.linkRecognition.text),
.inlineCodeLinkRegexKey = buildLinkRecognitionCacheKey(props.linkRecognition.inlineCode),
};
}
/**
* Thread-safe global measurement cache using an LRU (Least Recently Used) strategy.
* This ensures O(1) lookups while automatically discarding the oldest entries.
*/
class MeasurementCache {
public:
struct CacheEntry {
MeasurementCacheKey key;
CachedSize size;
};
static MeasurementCache &shared()
{
static MeasurementCache instance;
return instance;
}
bool get(const MeasurementCacheKey &key, CachedSize &outSize)
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = map_.find(key);
if (it == map_.end()) {
return false;
}
list_.splice(list_.begin(), list_, it->second);
outSize = it->second->size;
return true;
}
void set(const MeasurementCacheKey &key, CachedSize size)
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = map_.find(key);
if (it != map_.end()) {
it->second->size = size;
list_.splice(list_.begin(), list_, it->second);
return;
}
list_.push_front({key, size});
map_[key] = list_.begin();
if (map_.size() > kMaxEntries) {
auto &lastEntry = list_.back();
map_.erase(lastEntry.key);
list_.pop_back();
}
}
void removeMatchingMarkdown(const std::string &markdown)
{
std::lock_guard<std::mutex> lock(mutex_);
for (auto it = list_.begin(); it != list_.end();) {
if (it->key.markdown == markdown) {
map_.erase(it->key);
it = list_.erase(it);
} else {
++it;
}
}
}
private:
MeasurementCache() = default;
static constexpr size_t kMaxEntries = 512;
mutable std::mutex mutex_;
std::list<CacheEntry> list_;
std::unordered_map<MeasurementCacheKey, std::list<CacheEntry>::iterator, MeasurementCacheKeyHash> map_;
};
} // namespace facebook::react