Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 修复 Android 长会话消息显示不全且无法滚动 (#1905)

fangziyue0e910eeac47e
diff --git a/apps/mobile/src/__tests__/messageMarkdown.test.ts b/apps/mobile/src/__tests__/messageMarkdown.test.ts
index 705a7fec17..ac4994371b 100644
--- a/apps/mobile/src/__tests__/messageMarkdown.test.ts
+++ b/apps/mobile/src/__tests__/messageMarkdown.test.ts
@@ -6,6 +6,8 @@ import {
isMobileMarkdownImageDirectUrl,
mobileMarkdownImageTitle,
mobileMarkdownImageUrlForWorkdir,
+ mobileMarkdownImageAltChipText,
+ MOBILE_MARKDOWN_IMAGE_ALT_CHIP_MAX_UTF16_LENGTH,
mobileMarkdownInlineImageSize,
parseMobileMarkdown,
parseMobileMarkdownInlines,
@@ -1347,6 +1349,124 @@ describe('groupMobileMarkdownSelectableBlocks', () => {
expect(hasImage || isComplex).toBe(true);
}
});
+
+ it('can bound text runs by block count for tall native selectable text views', () => {
+ const blocks = parseMobileMarkdown([
+ '# 标题',
+ '',
+ '第一段',
+ '',
+ '- 列表项 A',
+ '- 列表项 B',
+ '',
+ '第二段',
+ ].join('\n'));
+ const groups = groupMobileMarkdownSelectableBlocks(blocks, { maxTextRunBlocks: 2 });
+ expect(groups.map((group) => group.type)).toEqual(['text_run', 'text_run', 'text_run']);
+ expect(groups.map((group) => (group.type === 'text_run' ? group.blocks.length : 0))).toEqual([2, 2, 1]);
+ });
+
+ it('can bound text runs by rendered inline text length', () => {
+ const blocks = parseMobileMarkdown([
+ '短段',
+ '',
+ '这是一段超过阈值的正文',
+ '',
+ '尾段',
+ ].join('\n'));
+ const groups = groupMobileMarkdownSelectableBlocks(blocks, { maxTextRunUtf16Length: 8 });
+ expect(groups.map((group) => group.type)).toEqual(['text_run', 'text_run', 'text_run']);
+ expect(groups.map((group) => (group.type === 'text_run' ? group.blocks.length : 0))).toEqual([1, 1, 2]);
+ });
+
+ it('counts rendered block separators when bounding text runs by text length', () => {
+ const blocks = parseMobileMarkdown(['aaaa', '', 'bbbb'].join('\n'));
+ const groups = groupMobileMarkdownSelectableBlocks(blocks, { maxTextRunUtf16Length: 8 });
+
+ expect(groups.map((group) => group.type)).toEqual(['text_run', 'text_run']);
+ expect(groups.map((group) => (group.type === 'text_run' ? group.blocks.length : 0))).toEqual([1, 1]);
+ });
+
+ it('splits a single oversized text block by rendered inline text length', () => {
+ const blocks = parseMobileMarkdown('a'.repeat(21));
+ const groups = groupMobileMarkdownSelectableBlocks(blocks, { maxTextRunUtf16Length: 8 });
+ expect(groups.map((group) => group.type)).toEqual(['text_run', 'text_run', 'text_run']);
+
+ const chunks = groups.flatMap((group) => (group.type === 'text_run' ? group.blocks : []));
+ expect(chunks.map((block) => (
+ block.inlines.map((inline) => (inline.type === 'image' ? inline.alt : inline.text)).join('')
+ ))).toEqual([
+ 'a'.repeat(8),
+ 'a'.repeat(8),
+ 'a'.repeat(5),
+ ]);
+ expect(chunks.map((block) => block.textRunContinuation === true)).toEqual([false, true, true]);
+ expect(groups.map((group) => (
+ group.type === 'text_run' && group.textRunContinuation === true
+ ))).toEqual([false, true, true]);
+ });
+
+ it('does not split surrogate pairs when a limit falls before an emoji', () => {
+ const text = `${'a'.repeat(7)}😀b`;
+ const blocks = parseMobileMarkdown(text);
+ const groups = groupMobileMarkdownSelectableBlocks(blocks, { maxTextRunUtf16Length: 8 });
+ const chunks = groups.flatMap((group) => (group.type === 'text_run' ? group.blocks : []));
+
+ const chunkText = chunks.map((block) => (
+ block.inlines.map((inline) => (inline.type === 'image' ? inline.alt : inline.text)).join('')
+ ));
+ expect(chunkText).toEqual(['a'.repeat(7), '😀b']);
+ expect(chunkText.join('')).toBe(text);
+ });
+
+ it('keeps oversized non-direct image alt text in one image inline while bounding rendered chip text', () => {
+ const alt = 'a'.repeat(MOBILE_MARKDOWN_IMAGE_ALT_CHIP_MAX_UTF16_LENGTH + 21);
+ const blocks = parseMobileMarkdown(`![${alt}](docs/local-image.png)`);
+ const groups = groupMobileMarkdownSelectableBlocks(blocks, { maxTextRunUtf16Length: 1800 });
+ const chunks = groups.flatMap((group) => (group.type === 'text_run' ? group.blocks : []));
+ const imageInlines = chunks.flatMap((block) => block.inlines.filter((inline) => inline.type === 'image'));
+
+ expect(groups.map((group) => group.type)).toEqual(['text_run']);
+ expect(imageInlines).toHaveLength(1);
+ expect(imageInlines[0]).toMatchObject({ alt, url: 'docs/local-image.png' });
+ expect(mobileMarkdownImageAltChipText(imageInlines[0].alt)).toHaveLength(
+ MOBILE_MARKDOWN_IMAGE_ALT_CHIP_MAX_UTF16_LENGTH,
+ );
+ expect(mobileMarkdownImageAltChipText(imageInlines[0].alt).endsWith('…')).toBe(true);
+ });
+
+ it('does not split surrogate pairs when truncating oversized image alt chip text', () => {
+ const alt = `${'a'.repeat(MOBILE_MARKDOWN_IMAGE_ALT_CHIP_MAX_UTF16_LENGTH - 1)}😀b`;
+ const chipText = mobileMarkdownImageAltChipText(alt);
+
+ expect(chipText).toHaveLength(MOBILE_MARKDOWN_IMAGE_ALT_CHIP_MAX_UTF16_LENGTH);
+ expect(chipText).toBe(`${'a'.repeat(MOBILE_MARKDOWN_IMAGE_ALT_CHIP_MAX_UTF16_LENGTH - 1)}…`);
+ expect(chipText).not.toContain('\uD83D');
+ expect(chipText).not.toContain('\uDE00');
+ });
+
+ it('counts rendered list marker spaces when splitting long list items', () => {
+ const blocks = parseMobileMarkdown('- abcdefghij');
+ const groups = groupMobileMarkdownSelectableBlocks(blocks, { maxTextRunUtf16Length: 8 });
+ const chunks = groups.flatMap((group) => (group.type === 'text_run' ? group.blocks : []));
+
+ expect(chunks.map((block) => (
+ block.inlines.map((inline) => (inline.type === 'image' ? inline.alt : inline.text)).join('')
+ ))).toEqual(['abcdef', 'ghij']);
+ expect(chunks.map((block) => block.textRunContinuation === true)).toEqual([false, true]);
+ });
+
+ it('treats fractional text run limits below one as disabled', () => {
+ const blocks = parseMobileMarkdown(['first', '', 'second'].join('\n'));
+ const groups = groupMobileMarkdownSelectableBlocks(blocks, {
+ maxTextRunBlocks: 0.5,
+ maxTextRunUtf16Length: 0.5,
+ });
+ expect(groups).toHaveLength(1);
+ expect(groups[0].type).toBe('text_run');
+ if (groups[0].type !== 'text_run') throw new Error('expected text_run');
+ expect(groups[0].blocks).toHaveLength(2);
+ });
});
describe('LaTeX math(块级 $$ 围栏与 inline $ 定界符)', () => {
diff --git a/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts b/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts
index 0eb80edaca..1089ad6066 100644
--- a/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/messageSelectionDesktopFirst.test.ts
@@ -52,9 +52,16 @@ describe('mobile message text selection', () => {
expect(markdownBodySource).toContain('selectable={inlinesSelectable(block.inlines)}');
// 跨段选择:连续纯文本块合并进同一个原生文本视图(text_run),原生选择手柄可横跨段落。
- expect(markdownBodySource).toContain('groupMobileMarkdownSelectableBlocks(blocks)');
+ // Android 上长 selectable Text 分块,避免单个超高原生文本视图干扰列表测高/滚动。
+ expect(markdownBodySource).toContain('ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS');
+ expect(markdownBodySource).toContain('groupMobileMarkdownSelectableBlocks(blocks, textRunGroupingOptions)');
expect(markdownBodySource).toContain('testID="message.markdownTextRun"');
expect(markdownBodySource).toContain("lineHeight: layout.markdownBodyGap");
+ expect(markdownBodySource).toContain('!block.textRunContinuation');
+ expect(markdownBodySource).toContain('isTextRunContinuationGroup(group)');
+ expect(markdownBodySource).toContain('height: layout.markdownBodyGap');
+ expect(markdownBodySource).not.toContain('{ gap: layout.markdownBodyGap }');
+ expect(source).toContain('mobileMarkdownImageAltChipText(inline.alt)');
expect(markdownBodySource).toContain('selectable={inlinesSelectable(cell)}');
expect(markdownBodySource).toContain('selectable={selectable === true}');
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index d732460786..bca93debb9 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -154,6 +154,7 @@ import {
import {
groupMobileMarkdownSelectableBlocks,
isMobileMarkdownImageDirectUrl,
+ mobileMarkdownImageAltChipText,
mobileMarkdownImageTitle,
mobileMarkdownImageUrlForWorkdir,
mobileMarkdownInlineImageSize,
@@ -161,6 +162,7 @@ import {
parseMobileMarkdownInlines,
type MobileMarkdownBlockGroup,
type MobileMarkdownInline,
+ type MobileMarkdownTextRunGroupingOptions,
} from '@/session/messageMarkdown';
import {
extractSessionLinkIds,
@@ -324,6 +326,12 @@ const MOBILE_PROGRAMMATIC_ANIMATED_SCROLL_SETTLE_MS = 1400;
/** Cold-open history fill is useful, but bounded so a short/duplicate host page cannot drain history forever. */
const MAX_INITIAL_HISTORY_AUTOFILL_PAGES = 3;
const MOBILE_MESSAGE_ESTIMATED_ITEM_SIZE = 140;
+const ANDROID_SELECTABLE_TEXT_RUN_MAX_BLOCKS = 12;
+const ANDROID_SELECTABLE_TEXT_RUN_MAX_UTF16_LENGTH = 1800;
+const ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS: MobileMarkdownTextRunGroupingOptions = {
+ maxTextRunBlocks: ANDROID_SELECTABLE_TEXT_RUN_MAX_BLOCKS,
+ maxTextRunUtf16Length: ANDROID_SELECTABLE_TEXT_RUN_MAX_UTF16_LENGTH,
+};
/** Running work groups expose only the same latest-five activity window as desktop. */
const MAX_LIVE_WORK_ACTIVITIES = 5;
// LegendList 预渲距离(px,视口外每侧):约 1 屏,挂载集小 → 滚动 mount 帧压进一帧内(见 listperf 实测)。
@@ -422,6 +430,10 @@ function MarkdownSelectableSpan(props: ComponentProps<typeof Text>) {
return <UITextView maxFontSizeMultiplier={MAX_FONT_SIZE_MULTIPLIER} {...props} />;
}
+function isTextRunContinuationGroup(group: MobileMarkdownBlockGroup): boolean {
+ return group.type === 'text_run' && group.textRunContinuation === true;
+}
+
/** Composer-ready user message body with product quotes kept out of raw text. */
export interface MobileMessageDraft {
document: ComposerDocument;
@@ -3386,8 +3398,16 @@ function MarkdownBody({
),
[onOpenSessionLink, openMarkdownImage, sessionLinkTitles, sessionReferenceDetails, streaming, styles],
);
+ const textRunGroupingOptions = selectable === true && Platform.OS === 'android'
+ ? ANDROID_SELECTABLE_TEXT_RUN_GROUPING_OPTIONS
+ : undefined;
// 连续纯文本块合并为 text_run(跨段选择),代码块/表格/mermaid/含直连图块保持独立。
- const groups = useMemo(() => groupMobileMarkdownSelectableBlocks(blocks), [blocks]);
+ // Android selectable Text 在超长原生文本视图里会偶发高度/滚动协商异常,长 run 分块
+ // 后仍保留块内跨段选择,同时避免单个 LegendList item 内出现巨型 selectable Text。
+ const groups = useMemo(
+ () => groupMobileMarkdownSelectableBlocks(blocks, textRunGroupingOptions),
+ [blocks, textRunGroupingOptions],
+ );
// 块可选中且 iOS → 嵌套 span 必须是 UITextView 家族;其余场景缺省 RN Text。
const spanFor = useCallback((blockSelectable: boolean) => (
blockSelectable && allowIosUITextView && Platform.OS === 'ios'
@@ -3397,7 +3417,8 @@ function MarkdownBody({
// 文本运行组:连续纯文本块(段落/标题/列表项)合进同一个原生文本视图,
// 原生选择手柄即可横跨段落(单个 text view 是 iOS/Android 原生选择的天然边界)。
// 段间距用「lineHeight = markdownBodyGap 的空行 span」还原:原生文本树内没有块级 gap 可用,
- // 一个高度恰为 gap 的空行在视觉上与原块间距一致。列表项在树内表达为「marker 前缀 span + 正文」
+ // 一个高度恰为 gap 的空行在视觉上与原块间距一致。由单块切出的 continuation 不插间距。
+ // 列表项在树内表达为「marker 前缀 span + 正文」
// (无悬挂缩进;任务项以 ☑/☐ 字符替代原边框小方块)。
const renderTextRun = (group: Extract<MobileMarkdownBlockGroup, { type: 'text_run' }>): ReactNode => {
const runSelectable = selectable === true;
@@ -3412,7 +3433,7 @@ function MarkdownBody({
>
{group.blocks.flatMap((block, index) => {
const spans: ReactNode[] = [];
- if (index > 0) {
+ if (index > 0 && !block.textRunContinuation) {
spans.push(
<RunSpan key={`${block.key}:gap`} style={{ lineHeight: layout.markdownBodyGap }}>
{'\n\n'}
@@ -3422,7 +3443,7 @@ function MarkdownBody({
const baseStyle: StyleProp<TextStyle> = block.type === 'heading'
? [styles.markdownHeading, headingSizeStyle(styles, block.level)]
: styles.messageText;
- if (block.type === 'list_item') {
+ if (block.type === 'list_item' && !block.textRunContinuation) {
const task = typeof block.checked === 'boolean';
spans.push(
<RunSpan
@@ -3441,15 +3462,16 @@ function MarkdownBody({
};
return (
<View
- style={[styles.markdownBody, { gap: layout.markdownBodyGap }]}
+ style={styles.markdownBody}
testID="message.markdownBody"
>
- {groups.map((group) => {
- if (group.type === 'text_run') {
- return renderTextRun(group);
- }
- const block = group.block;
- if (block.type === 'mermaid') {
+ {groups.flatMap((group, groupIndex) => {
+ const renderedGroup = (() => {
+ if (group.type === 'text_run') {
+ return renderTextRun(group);
+ }
+ const block = group.block;
+ if (block.type === 'mermaid') {
// 内联图表按「图片」形态呈现:无卡片 chrome、无标签文字、无按钮,
// 就是一块圆角图表;点击任意位置打开沉浸式全屏详情(透明 Pressable
// 盖住整块——WebView 会吞掉触摸事件,不盖层拿不到点击)。
@@ -3625,6 +3647,14 @@ function MarkdownBody({
{renderInlines(block.inlines, spanFor(inlinesSelectable(block.inlines)))}
</MarkdownSelectableText>
);
+ })();
+ if (groupIndex === 0 || isTextRunContinuationGroup(group)) {
+ return [renderedGroup];
+ }
+ return [
+ <View key={`${group.key}:body-gap`} style={{ height: layout.markdownBodyGap }} />,
+ renderedGroup,
+ ];
})}
</View>
);
@@ -3986,6 +4016,9 @@ function renderInline(
// xdt 系非直连图:RN Image 无法直接加载内部 scheme,渲染可点 chip,
// 点开后由 ImageLightbox 经 remote-media resolver 取图。
if (!isMobileMarkdownImageDirectUrl(inline.url)) {
+ const imageChipText = inline.alt
+ ? mobileMarkdownImageAltChipText(inline.alt)
+ : i18n.t('message.renderer.imageFallbackTitle');
return (
<SpanText
key={spanKey(`image:${index}:${inline.url}`)}
@@ -3993,7 +4026,7 @@ function renderInline(
style={clickableInlineStyle(styles, openImageChip, ctx.baseStyle)}
testID="message.markdownInlineImageChip"
>
- {inline.alt || i18n.t('message.renderer.imageFallbackTitle')}
+ {imageChipText}
</SpanText>
);
}
@@ -6098,7 +6131,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
fontSize: typeScale.caption,
lineHeight: lineHeight.caption,
},
- markdownBody: { gap: 10 },
+ markdownBody: {},
// 外链 / 会话深链等一切可点行内元素:**只有下划线**,不加粗、不换色、不换字体
// (DESIGN.md §14.5;GitHub 的 `.markdown-body a` 同样只有 text-decoration)。
//
diff --git a/apps/mobile/src/session/messageMarkdown.ts b/apps/mobile/src/session/messageMarkdown.ts
index 62fdf3feea..bdbc7fa000 100644
--- a/apps/mobile/src/session/messageMarkdown.ts
+++ b/apps/mobile/src/session/messageMarkdown.ts
@@ -412,25 +412,68 @@ export function mobileMarkdownImageUrlForWorkdir(
* 它们承载非文本结构(横向滚动 / 边框 / 内嵌 View),不能进原生文本树,选择也天然止步于此。
*/
export type MobileMarkdownTextRunBlock =
- Extract<MobileMarkdownBlock, { type: 'paragraph' | 'heading' | 'list_item' }>;
+ Extract<MobileMarkdownBlock, { type: 'paragraph' | 'heading' | 'list_item' }>
+ & { textRunContinuation?: boolean };
export type MobileMarkdownBlockGroup =
- | { type: 'text_run'; key: string; blocks: MobileMarkdownTextRunBlock[] }
+ | { type: 'text_run'; key: string; blocks: MobileMarkdownTextRunBlock[]; textRunContinuation?: boolean }
| { type: 'single'; key: string; block: MobileMarkdownBlock };
+export interface MobileMarkdownTextRunGroupingOptions {
+ /**
+ * Upper bound for one selectable native text view. Undefined keeps the
+ * historical "merge until a non-text block" behavior.
+ */
+ maxTextRunBlocks?: number;
+ /** Same guard by rendered inline text length, measured in JS UTF-16 units. */
+ maxTextRunUtf16Length?: number;
+}
+
+const MOBILE_MARKDOWN_TEXT_RUN_BLOCK_SEPARATOR_UTF16_LENGTH = 2;
+export const MOBILE_MARKDOWN_IMAGE_ALT_CHIP_MAX_UTF16_LENGTH = 256;
+
export function groupMobileMarkdownSelectableBlocks(
blocks: readonly MobileMarkdownBlock[],
+ options?: MobileMarkdownTextRunGroupingOptions,
): MobileMarkdownBlockGroup[] {
const groups: MobileMarkdownBlockGroup[] = [];
let run: MobileMarkdownTextRunBlock[] = [];
+ let runTextLength = 0;
+ const maxTextRunBlocks = normalizePositiveLimit(options?.maxTextRunBlocks);
+ const maxTextRunUtf16Length = normalizePositiveLimit(options?.maxTextRunUtf16Length);
const flushRun = () => {
if (run.length === 0) return;
- groups.push({ type: 'text_run', key: `run:${run[0].key}`, blocks: run });
+ groups.push({
+ type: 'text_run',
+ key: `run:${run[0].key}`,
+ blocks: run,
+ ...(run[0].textRunContinuation ? { textRunContinuation: true } : {}),
+ });
run = [];
+ runTextLength = 0;
};
for (const block of blocks) {
if (isTextRunBlock(block)) {
- run.push(block);
+ for (const chunk of splitOversizedTextRunBlock(block, maxTextRunUtf16Length)) {
+ const blockTextLength = mobileMarkdownTextRunBlockLength(chunk);
+ const separatorLength = run.length > 0 && !chunk.textRunContinuation
+ ? MOBILE_MARKDOWN_TEXT_RUN_BLOCK_SEPARATOR_UTF16_LENGTH
+ : 0;
+ if (
+ run.length > 0
+ && (
+ run.length >= maxTextRunBlocks
+ || runTextLength + separatorLength + blockTextLength > maxTextRunUtf16Length
+ )
+ ) {
+ flushRun();
+ }
+ const pushedSeparatorLength = run.length > 0 && !chunk.textRunContinuation
+ ? MOBILE_MARKDOWN_TEXT_RUN_BLOCK_SEPARATOR_UTF16_LENGTH
+ : 0;
+ run.push(chunk);
+ runTextLength += pushedSeparatorLength + blockTextLength;
+ }
} else {
flushRun();
groups.push({ type: 'single', key: block.key, block });
@@ -450,6 +493,162 @@ function isTextRunBlock(block: MobileMarkdownBlock): block is MobileMarkdownText
);
}
+function normalizePositiveLimit(value: number | undefined): number {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
+ return Number.POSITIVE_INFINITY;
+ }
+ const normalized = Math.floor(value);
+ return normalized > 0 ? normalized : Number.POSITIVE_INFINITY;
+}
+
+function mobileMarkdownTextRunBlockLength(block: MobileMarkdownTextRunBlock): number {
+ const inlineLength = block.inlines.reduce((total, inline) => total + mobileMarkdownInlineTextLength(inline), 0);
+ if (block.type === 'list_item' && !block.textRunContinuation) {
+ return inlineLength + mobileMarkdownListMarkerText(block).length;
+ }
+ return inlineLength;
+}
+
+function mobileMarkdownInlineTextLength(inline: MobileMarkdownInline): number {
+ if (inline.type === 'image') {
+ return mobileMarkdownImageAltChipText(inline.alt).length;
+ }
+ return inline.text.length;
+}
+
+export function mobileMarkdownImageAltChipText(alt: string): string {
+ if (alt.length <= MOBILE_MARKDOWN_IMAGE_ALT_CHIP_MAX_UTF16_LENGTH) return alt;
+ const end = safeUtf16SliceEnd(alt, 0, MOBILE_MARKDOWN_IMAGE_ALT_CHIP_MAX_UTF16_LENGTH - 1);
+ return `${alt.slice(0, end)}…`;
+}
+
+function splitOversizedTextRunBlock(
+ block: MobileMarkdownTextRunBlock,
+ maxTextRunUtf16Length: number,
+): MobileMarkdownTextRunBlock[] {
+ if (
+ !Number.isFinite(maxTextRunUtf16Length)
+ || mobileMarkdownTextRunBlockLength(block) <= maxTextRunUtf16Length
+ ) {
+ return [block];
+ }
+
+ const chunks: MobileMarkdownInline[][] = [];
+ let current: MobileMarkdownInline[] = [];
+ let currentTextLength = 0;
+ const currentLimit = () => Math.max(
+ 1,
+ maxTextRunUtf16Length - (chunks.length === 0 ? mobileMarkdownTextRunBlockPrefixLength(block) : 0),
+ );
+ const flushCurrent = () => {
+ if (current.length === 0) return;
+ chunks.push(current);
+ current = [];
+ currentTextLength = 0;
+ };
+ const appendInlineTextChunks = (
+ text: string,
+ buildInline: (text: string) => MobileMarkdownInline,
+ ) => {
+ let start = 0;
+ while (start < text.length) {
+ if (currentTextLength >= currentLimit()) flushCurrent();
+ const capacity = currentLimit() - currentTextLength;
+ if (
+ currentTextLength > 0
+ && capacity === 1
+ && startsWithSurrogatePair(text, start)
+ ) {
+ flushCurrent();
+ continue;
+ }
+ const end = safeUtf16SliceEnd(text, start, capacity);
+ current.push(buildInline(text.slice(start, end)));
+ currentTextLength += end - start;
+ start = end;
+ }
+ };
+
+ for (const inline of block.inlines) {
+ if (inline.type === 'image') {
+ const inlineLength = mobileMarkdownInlineTextLength(inline);
+ if (current.length > 0 && currentTextLength + inlineLength > currentLimit()) {
+ flushCurrent();
+ }
+ current.push(inline);
+ currentTextLength += inlineLength;
+ if (currentTextLength >= currentLimit()) flushCurrent();
+ continue;
+ }
+
+ appendInlineTextChunks(inline.text, (text) => ({ ...inline, text }));
+ }
+ flushCurrent();
+
+ if (chunks.length <= 1) return [block];
+ return chunks.map((inlines, index) => cloneTextRunBlockChunk(block, inlines, index));
+}
+
+function mobileMarkdownTextRunBlockPrefixLength(block: MobileMarkdownTextRunBlock): number {
+ if (block.type !== 'list_item' || block.textRunContinuation) return 0;
+ return mobileMarkdownListMarkerText(block).length;
+}
+
+function mobileMarkdownListMarkerText(block: Extract<MobileMarkdownTextRunBlock, { type: 'list_item' }>): string {
+ if (typeof block.checked === 'boolean') return block.checked ? '☑ ' : '☐ ';
+ return block.ordered ? `${block.marker} ` : '• ';
+}
+
+function cloneTextRunBlockChunk(
+ block: MobileMarkdownTextRunBlock,
+ inlines: MobileMarkdownInline[],
+ index: number,
+): MobileMarkdownTextRunBlock {
+ const key = index === 0 ? block.key : `${block.key}:split:${index}`;
+ const continuation = index > 0 ? { textRunContinuation: true } : {};
+ if (block.type === 'paragraph') return { ...block, key, inlines, ...continuation };
+ if (block.type === 'heading') return { ...block, key, inlines, ...continuation };
+ return {
+ ...block,
+ key,
+ inlines,
+ ...continuation,
+ };
+}
+
+function safeUtf16SliceEnd(text: string, start: number, maxLength: number): number {
+ const length = Math.max(1, maxLength);
+ if (length === 1 && startsWithSurrogatePair(text, start)) {
+ return start + 2;
+ }
+ let end = Math.min(text.length, start + length);
+ if (
+ end < text.length
+ && end > start
+ && isHighSurrogate(text.charCodeAt(end - 1))
+ && isLowSurrogate(text.charCodeAt(end))
+ ) {
+ end -= 1;
+ }
+ return end > start ? end : Math.min(text.length, start + 1);
+}
+
+function startsWithSurrogatePair(text: string, start: number): boolean {
+ return (
+ start + 1 < text.length
+ && isHighSurrogate(text.charCodeAt(start))
+ && isLowSurrogate(text.charCodeAt(start + 1))
+ );
+}
+
+function isHighSurrogate(value: number): boolean {
+ return value >= 0xD800 && value <= 0xDBFF;
+}
+
+function isLowSurrogate(value: number): boolean {
+ return value >= 0xDC00 && value <= 0xDFFF;
+}
+
const MARKDOWN_INLINE_IMAGE_DEFAULT_WIDTH = 150;
const MARKDOWN_INLINE_IMAGE_MAX_EDGE = 220;