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): 修复 Markdown 预览滚动与文件翻页冲突 (#5052)

DavidShenXDd90b5a94afa8
diff --git a/apps/mobile/app/files/preview/[sessionId].tsx b/apps/mobile/app/files/preview/[sessionId].tsx
index 7b3d6a2406..29b0621dc4 100644
--- a/apps/mobile/app/files/preview/[sessionId].tsx
+++ b/apps/mobile/app/files/preview/[sessionId].tsx
@@ -198,9 +198,15 @@ export default function RemoteFilePreviewScreen() {
// 渲染 / 源码的切换状态在子页里,所以由子页按页 key 上报;setter 用 key 比对而不是
// 直接存布尔,避免翻页时「旧页报 false」与「新页报 true」的先后顺序决定结果。
const [htmlPanPageKey, setHtmlPanPageKey] = useState<string | null>(null);
+ const [markdownPagerPageKey, setMarkdownPagerPageKey] = useState<string | null>(null);
const reportHtmlPan = useCallback((key: string, wants: boolean) => {
setHtmlPanPageKey((prev) => (wants ? key : (prev === key ? null : prev)));
}, []);
+ // Markdown WebView 的纵向滚动和宽公式横移保留在内层;正文明确横滑由文档
+ // 回调后在这里驱动同一个 pager,避免 WebView 与 FlatList 争抢触摸序列。
+ const reportMarkdownPager = useCallback((key: string, wants: boolean) => {
+ setMarkdownPagerPageKey((prev) => (wants ? key : (prev === key ? null : prev)));
+ }, []);
const showNotice = useCallback((text: string) => {
setNotice(text);
@@ -339,6 +345,12 @@ export default function RemoteFilePreviewScreen() {
const current = siblings?.[pageIndex] ?? null;
const pagerRef = useRef<FlatList<FileBrowserGridItem>>(null);
+ const moveMarkdownPager = useCallback((key: string, direction: 'previous' | 'next') => {
+ if (key !== current?.key || !siblings) return;
+ const next = pageIndex + (direction === 'next' ? 1 : -1);
+ if (next < 0 || next >= siblings.length) return;
+ pagerRef.current?.scrollToOffset({ animated: true, offset: next * pageWidth });
+ }, [current?.key, pageIndex, pageWidth, siblings]);
// 当前可见文件路径镜像(pager 重建锚定用;不能进上面 effect 的依赖,否则
// 每次翻页都会重列目录)。
const currentRelPathRef = useRef<string | null>(null);
@@ -569,6 +581,8 @@ export default function RemoteFilePreviewScreen() {
// 对话界面之后继续跑脚本。screenFocused 翻假即卸载。
visible={screenFocused && index === pageIndex}
onHtmlPanChange={reportHtmlPan}
+ onMarkdownPagerChange={reportMarkdownPager}
+ onMarkdownPageSwipe={moveMarkdownPager}
exportToUrl={exportToUrl}
prepareHtmlPreview={prepareHtmlPreview}
item={item}
@@ -613,7 +627,7 @@ export default function RemoteFilePreviewScreen() {
// 超出视口的内容永远看不到。手势仲裁(区分内层平移与翻页)在 RN 上要自己写一套
// 竞态裁决,属独立改动;这里沿用本文件对 PDF 已经采用的同一口径 —— 想翻页就切到
// 「源码」态(源码是竖向列表,不冲突),或 Done 返回列表。
- scrollEnabled={current.previewKind !== 'pdf' && htmlPanPageKey !== current.key}
+ scrollEnabled={current.previewKind !== 'pdf' && htmlPanPageKey !== current.key && markdownPagerPageKey !== current.key}
showsHorizontalScrollIndicator={false}
windowSize={3}
/>
@@ -700,6 +714,8 @@ function FilePreviewPage({
maker,
onDownload,
onHtmlPanChange,
+ onMarkdownPagerChange,
+ onMarkdownPageSwipe,
onOpenLightbox,
onQuoteSelection,
readTextFile,
@@ -718,6 +734,8 @@ function FilePreviewPage({
onDownload(): void;
/** 上报本页是否处在 HTML 渲染态(外层 pager 据此让出横滑,仅文本页产出)。 */
onHtmlPanChange?: (key: string, wants: boolean) => void;
+ onMarkdownPagerChange?: (key: string, wants: boolean) => void;
+ onMarkdownPageSwipe?: (key: string, direction: 'previous' | 'next') => void;
onOpenLightbox(url: string): void;
/** chat-text-quote:markdown 渲染态的选中引用回调(仅文本页消费)。 */
onQuoteSelection?: (text: string) => void;
@@ -760,6 +778,8 @@ function FilePreviewPage({
htmlBrowserActions={htmlBrowserActions}
onDownload={onDownload}
onHtmlPanChange={onHtmlPanChange}
+ onMarkdownPagerChange={onMarkdownPagerChange}
+ onMarkdownPageSwipe={onMarkdownPageSwipe}
onQuoteSelection={onQuoteSelection}
readTextFile={readTextFile}
targetLine={targetLine}
@@ -933,6 +953,8 @@ function TextPreviewPage({
htmlBrowserActions,
onDownload,
onHtmlPanChange,
+ onMarkdownPagerChange,
+ onMarkdownPageSwipe,
onQuoteSelection,
readTextFile,
targetLine,
@@ -950,6 +972,8 @@ function TextPreviewPage({
onDownload(): void;
/** 上报本页是否处在 HTML 渲染态(外层 pager 据此让出横滑,见调用处说明)。 */
onHtmlPanChange?: (key: string, wants: boolean) => void;
+ onMarkdownPagerChange?: (key: string, wants: boolean) => void;
+ onMarkdownPageSwipe?: (key: string, direction: 'previous' | 'next') => void;
/** chat-text-quote:markdown 渲染态的选中引用回调(源码态暂不支持,见 PR 说明)。 */
onQuoteSelection?: (text: string) => void;
/** 屏级注入:readFile 带瞬断重试 + openLink(与列表/搜索/导出同路径)。 */
@@ -1067,6 +1091,12 @@ function TextPreviewPage({
onHtmlPanChange?.(item.key, htmlPanWanted);
return () => onHtmlPanChange?.(item.key, false);
}, [htmlPanWanted, item.key, onHtmlPanChange]);
+ const markdownPagerWanted = visible && richKind === 'markdown' && richView === 'rendered'
+ && state.status === 'ready';
+ useEffect(() => {
+ onMarkdownPagerChange?.(item.key, markdownPagerWanted);
+ return () => onMarkdownPagerChange?.(item.key, false);
+ }, [item.key, markdownPagerWanted, onMarkdownPagerChange]);
if (website) return visible ? <HtmlWebsiteBrowser
visit={website}
@@ -1159,7 +1189,13 @@ function TextPreviewPage({
/>
)
) : (
- <MarkdownFileReader markdown={ready?.content ?? ''} onQuoteSelection={onQuoteSelection} targetLine={targetLine} testID="filePreview.markdownRendered" />
+ <MarkdownFileReader
+ markdown={ready?.content ?? ''}
+ onPageSwipe={onMarkdownPageSwipe ? (direction) => onMarkdownPageSwipe(item.key, direction) : undefined}
+ onQuoteSelection={onQuoteSelection}
+ targetLine={targetLine}
+ testID="filePreview.markdownRendered"
+ />
)
) : state.status === 'loading' ? (
<View style={styles.centerFill}><ActivityIndicator color={colors.textTertiary} /></View>
diff --git a/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts b/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts
index fba78f7bbb..21e8dcc1c7 100644
--- a/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts
+++ b/apps/mobile/src/__tests__/conversationShareWebViewHtml.test.ts
@@ -51,6 +51,25 @@ function buildRichConversationHtml(): string {
}
describe('buildConversationShareHtml 富内容导出', () => {
+ it.each([
+ { contentWidth: 360, minWidth: 96, dark: false },
+ { contentWidth: 360, minWidth: 96, dark: true },
+ { contentWidth: 390, minWidth: 112, dark: false },
+ { contentWidth: 390, minWidth: 112, dark: true },
+ ])('分享表格保留列宽($contentWidth / dark=$dark),不套用文件预览等宽布局', ({ contentWidth, minWidth, dark }) => {
+ const html = buildConversationShareHtml({
+ allShareableIds: ['table'], colors: { ...colors, dark }, contentWidth,
+ selectedMessages: [{
+ clientId: 'table', kind: 'assistant',
+ body: '| A | B | C | D |\n| --- | --- | --- | --- |\n| Alpha | Beta | Gamma | Delta |',
+ }],
+ });
+ expect(html).toContain('<table>');
+ expect(html).toMatch(new RegExp(`th, td \\{[^}]*min-width:\\s*${minWidth}px`, 's'));
+ expect(html).toMatch(/table \{[^}]*display:\s*block[^}]*max-width:\s*100%[^}]*overflow-x:\s*auto/s);
+ expect(html).not.toMatch(/table \{[^}]*table-layout:\s*fixed/s);
+ });
+
it('继续脱敏跨行内格式和段落拆开的凭证', () => {
const html = buildConversationShareHtml({
allShareableIds: ['secret'], colors, contentWidth: 390,
diff --git a/apps/mobile/src/__tests__/filePreviewPagerWiring.test.ts b/apps/mobile/src/__tests__/filePreviewPagerWiring.test.ts
index 7a7dcbf3b6..092c29b406 100644
--- a/apps/mobile/src/__tests__/filePreviewPagerWiring.test.ts
+++ b/apps/mobile/src/__tests__/filePreviewPagerWiring.test.ts
@@ -37,7 +37,10 @@ describe('remote file preview pager wiring', () => {
it('HTML 渲染态同样让出外层横滑,让内层 WebView 能横向平移', () => {
// 固定宽度布局 / 放大后需要横向平移,pager 抢走手势就永远看不到超出视口的内容。
- expect(source).toContain("scrollEnabled={current.previewKind !== 'pdf' && htmlPanPageKey !== current.key}");
+ expect(source).toContain("scrollEnabled={current.previewKind !== 'pdf' && htmlPanPageKey !== current.key && markdownPagerPageKey !== current.key}");
+ const markdownReader = readSource('src/session/MarkdownFileReader.tsx');
+ expect(markdownReader).toContain('injectedJavaScript={onPageSwipe ? MARKDOWN_FILE_PAGER_SCRIPT : undefined}');
+ expect(markdownReader).toContain('onMessage={onPageSwipe ? handleMessage : undefined}');
// 让路状态按页 key 存,不存布尔:翻页时新旧两页的上报先后顺序不能决定结果。
expect(source).toContain('setHtmlPanPageKey((prev) => (wants ? key : (prev === key ? null : prev)))');
// 只有真的挂着 WebView 的那种组合才要横滑(资源还在取 → 页面是 spinner → 不禁滑);
diff --git a/apps/mobile/src/__tests__/markdownFilePager.test.ts b/apps/mobile/src/__tests__/markdownFilePager.test.ts
new file mode 100644
index 0000000000..739164a73f
--- /dev/null
+++ b/apps/mobile/src/__tests__/markdownFilePager.test.ts
@@ -0,0 +1,113 @@
+import { runInNewContext } from 'node:vm';
+import { describe, expect, it } from 'vitest';
+import { MARKDOWN_FILE_PAGER_SCRIPT, parseMarkdownPageSwipe } from '@/session/markdownFilePager';
+
+function reader(formulaTag = 'DIV', formulaWidth = 1200) {
+ const listeners = new Map<string, (event: unknown) => void>();
+ const messages: string[] = [];
+ const body = { nodeType: 1, parentElement: null };
+ const paragraph = { nodeType: 1, tagName: 'P', parentElement: body };
+ const formula = {
+ nodeType: 1, tagName: formulaTag, parentElement: body,
+ overflowX: 'auto', scrollWidth: formulaWidth, clientWidth: 380,
+ };
+ const formulaChild = { nodeType: 1, tagName: 'SPAN', parentElement: formula };
+ let selected = false;
+ const context = {
+ window: {
+ getSelection: () => ({ isCollapsed: !selected }),
+ getComputedStyle: (element: { overflowX?: string }) => ({ overflowX: element.overflowX }),
+ ReactNativeWebView: { postMessage: (message: string) => messages.push(message) },
+ },
+ document: {
+ body,
+ addEventListener: (type: string, listener: (event: unknown) => void, options: unknown) => {
+ expect(options).toEqual({ passive: true });
+ listeners.set(type, listener);
+ },
+ },
+ };
+ runInNewContext(MARKDOWN_FILE_PAGER_SCRIPT, context);
+ function touch(type: string, x: number, y: number, time = 0, target: unknown = paragraph, count = 1) {
+ const point = { identifier: 1, clientX: x, clientY: y };
+ listeners.get(type)?.({
+ target, timeStamp: time,
+ touches: type === 'touchend' ? [] : Array.from({ length: count }, () => point),
+ changedTouches: [point],
+ });
+ }
+ return { messages, touch, formulaChild, paragraph, select: () => { selected = true; } };
+}
+
+describe('Markdown reader paging', () => {
+ it.each([[-100, 'next'], [100, 'previous']])('pages after a deliberate %s px swipe', (dx, direction) => {
+ const r = reader();
+ r.touch('touchstart', 200, 100);
+ r.touch('touchmove', 200 + Number(dx), 103, 150);
+ expect(r.messages).toEqual([]);
+ r.touch('touchend', 200 + Number(dx), 103, 200);
+ expect(r.messages).toEqual([`markdown-page:${direction}`]);
+ });
+
+ it('lets vertical reading win permanently, even if the finger later moves horizontally', () => {
+ const r = reader();
+ r.touch('touchstart', 200, 300);
+ r.touch('touchmove', 203, 285, 30);
+ r.touch('touchmove', 80, 200, 200);
+ r.touch('touchend', 80, 200, 250);
+ expect(r.messages).toEqual([]);
+ });
+
+ it.each(['DIV', 'SPAN'])('keeps wide %s formula drags inside their scroll container, including at its edges', (tag) => {
+ const r = reader(tag);
+ for (const dx of [-200, 200]) {
+ r.touch('touchstart', 200, 100, 0, r.formulaChild);
+ r.touch('touchmove', 200 + dx, 100, 100, r.formulaChild);
+ r.touch('touchend', 200 + dx, 100, 200, r.formulaChild);
+ }
+ expect(r.messages).toEqual([]);
+ // A subsequent gesture in ordinary text can still page.
+ r.touch('touchstart', 200, 300);
+ r.touch('touchend', 80, 300, 200);
+ expect(r.messages).toEqual(['markdown-page:next']);
+ });
+
+ it('allows paging over an inline formula that fits without horizontal overflow', () => {
+ const r = reader('SPAN', 380);
+ r.touch('touchstart', 200, 100, 0, r.formulaChild);
+ r.touch('touchmove', 80, 100, 150, r.formulaChild);
+ r.touch('touchend', 80, 100, 200, r.formulaChild);
+ expect(r.messages).toEqual(['markdown-page:next']);
+ });
+
+ it('ignores slow short swipes but accepts a deliberate short flick', () => {
+ const r = reader();
+ r.touch('touchstart', 200, 100);
+ r.touch('touchmove', 170, 100, 150);
+ r.touch('touchend', 170, 100, 400);
+ expect(r.messages).toEqual([]);
+ r.touch('touchstart', 200, 100);
+ r.touch('touchend', 170, 100, 40);
+ expect(r.messages).toEqual(['markdown-page:next']);
+ });
+
+ it.each(['selection', 'long-press', 'multi-touch', 'cancel', 'link'])('does not page during %s', (kind) => {
+ const r = reader();
+ const target = kind === 'link' ? { nodeType: 1, tagName: 'A', parentElement: r.paragraph } : r.paragraph;
+ r.touch('touchstart', 200, 100, 0, target);
+ if (kind === 'selection') r.select();
+ if (kind === 'multi-touch') r.touch('touchstart', 200, 100, 10, target, 2);
+ if (kind === 'cancel') r.touch('touchcancel', 200, 100, 10);
+ r.touch('touchmove', 80, 100, kind === 'long-press' ? 700 : 100, target);
+ r.touch('touchend', 80, 100, 800, target);
+ expect(r.messages).toEqual([]);
+ });
+
+ it('accepts only the two page messages at the host boundary', () => {
+ expect(parseMarkdownPageSwipe('markdown-page:next')).toBe('next');
+ expect(parseMarkdownPageSwipe('markdown-page:previous')).toBe('previous');
+ for (const data of ['', '{}', 'markdown-page:other', 'markdown-page:next\n']) {
+ expect(parseMarkdownPageSwipe(data)).toBeNull();
+ }
+ });
+});
diff --git a/apps/mobile/src/__tests__/selectableMarkdownHtml.test.ts b/apps/mobile/src/__tests__/selectableMarkdownHtml.test.ts
index d8effd0072..0036cb1615 100644
--- a/apps/mobile/src/__tests__/selectableMarkdownHtml.test.ts
+++ b/apps/mobile/src/__tests__/selectableMarkdownHtml.test.ts
@@ -39,6 +39,25 @@ describe('buildSelectableMarkdownHtml 渲染态行定位', () => {
});
});
+describe('buildSelectableMarkdownHtml 移动阅读视口', () => {
+ const css = () => buildSelectableMarkdownHtml('# 标题');
+
+ it('正文沿用文件预览的左右安全边距且根视口不横向滚动', () => {
+ expect(css()).toMatch(/body \{[^}]*box-sizing:\s*border-box[^}]*padding:\s*0 16px[^}]*overflow-x:\s*hidden[^}]*touch-action:\s*auto/s);
+ expect(buildSelectableMarkdownHtml('# 标题', { horizontalPadding: 12 })).toContain('padding: 0 12px;');
+ expect(css()).toMatch(/html \{[^}]*overflow-x:\s*hidden[^}]*overscroll-behavior-x:\s*none[^}]*touch-action:\s*auto/s);
+ expect(css()).toMatch(/#xdt-content \{[^}]*max-width:\s*100%[^}]*min-width:\s*0[^}]*width:\s*100%/s);
+ });
+
+ it('表格适应视口,宽公式保留独立横向滚动且不撑宽文档', () => {
+ expect(css()).toMatch(/table \{[^}]*table-layout:\s*fixed[^}]*width:\s*100%/s);
+ expect(css()).toMatch(/th, td \{[^}]*min-width:\s*0[^}]*overflow-wrap:\s*anywhere[^}]*word-break:\s*break-word/s);
+ expect(css()).toMatch(/\.xdt-math-block \{[^}]*max-width:\s*100%[^}]*min-width:\s*0[^}]*overflow-x:\s*auto/s);
+ expect(css()).toMatch(/\.xdt-math-inline \{[^}]*display:\s*inline-block[^}]*max-width:\s*100%[^}]*overflow-x:\s*auto/s);
+ expect(css()).not.toMatch(/touch-action:\s*pan-x/);
+ });
+});
+
/**
* 代码块语法着色的 WebView 输出。
*
diff --git a/apps/mobile/src/debug/markdownPreviewFixture.ts b/apps/mobile/src/debug/markdownPreviewFixture.ts
new file mode 100644
index 0000000000..e3fb57a056
--- /dev/null
+++ b/apps/mobile/src/debug/markdownPreviewFixture.ts
@@ -0,0 +1,27 @@
+/** Dev visual-mock files for black-box reading, formula panning and file paging. */
+export const markdownPreviewFixture = [
+ '# Markdown reading fixture',
+ '',
+ 'Short inline formula $x^2 + y^2 = z^2$ stays in this paragraph.',
+ '',
+ 'Wide inline formula $\\frac{'
+ + Array.from({ length: 32 }, (_, index) => `x_{${index}}`).join(' + ')
+ + '}{2} = \\mathrm{INLINEEND}$ followed by readable text.',
+ '',
+ '## Wide formula',
+ '',
+ '$$',
+ Array.from({ length: 24 }, (_, index) => `x_{${index}}`).join(' + ') + ' = \\mathrm{END}',
+ '$$',
+ '',
+ '## Wide table',
+ '',
+ '| Name | Description | Long value | Status |',
+ '| --- | --- | --- | --- |',
+ '| A | Markdown table wrapping | abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz | Complete |',
+ '',
+ ...Array.from({ length: 30 }, (_, index) => (
+ `## Section ${index + 1}\n\nReading paragraph ${index + 1}. Scroll vertically with a slight sideways drift. `
+ + 'A horizontal swipe in this paragraph switches files. Long press to select this text.\n'
+ )),
+].join('\n');
diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.ts
index 172e5c020b..37b924c761 100644
--- a/apps/mobile/src/debug/visualMock.ts
+++ b/apps/mobile/src/debug/visualMock.ts
@@ -18,6 +18,7 @@ import type {
RemoteTextFilePreviewResult,
} from '@/device-link/mobileMakerTransport';
import { remoteSessionStore } from '@/session/remoteSessionStore';
+import { markdownPreviewFixture } from '@/debug/markdownPreviewFixture';
import type { InputProjection, PendingInteraction, RemoteMessage, RemoteSession } from '@/session/types';
export const VISUAL_MOCK_DEVICE_ID = 'cindy-visual-mock-mac';
@@ -703,7 +704,7 @@ function handleVisualMockFileBrowser(input: unknown): unknown {
elapsedMs: 8,
} satisfies FileBrowserListAllFilesResult;
}
- if (op === 'readFile') return visualMockReadFile();
+ if (op === 'readFile') return visualMockReadFile(input);
if (op === 'searchCollect') {
return {
matches: [
@@ -754,13 +755,17 @@ function visualMockFileBrowserEntries() {
];
}
-function visualMockReadFile(): FileBrowserReadFileResult {
+function visualMockReadFile(input: unknown): FileBrowserReadFileResult {
+ const relPath = input && typeof input === 'object' && 'relPath' in input
+ ? String(input.relPath) : 'visual-report.md';
+ const content = relPath === 'README.md' ? markdownPreviewFixture
+ : '# Next file\n\nSwipe right to return to the Markdown reading fixture.';
return {
ok: true,
data: {
- relPath: 'visual-report.md',
- content: '# Visual mock\n\nThis file preview is served by the mobile dev-only visual mock.',
- size: 78,
+ relPath,
+ content,
+ size: content.length,
mtimeMs: NOW,
},
};
diff --git a/apps/mobile/src/session/MarkdownFileReader.tsx b/apps/mobile/src/session/MarkdownFileReader.tsx
index 9731ed2c6d..e47dcc75c1 100644
--- a/apps/mobile/src/session/MarkdownFileReader.tsx
+++ b/apps/mobile/src/session/MarkdownFileReader.tsx
@@ -20,17 +20,21 @@ import { WebView } from 'react-native-webview';
import type { ShouldStartLoadRequest } from 'react-native-webview/lib/WebViewTypes';
import { buildSelectableMarkdownHtml } from '@/session/selectableMarkdownHtml';
+import { MARKDOWN_FILE_PAGER_SCRIPT, parseMarkdownPageSwipe } from '@/session/markdownFilePager';
import { selectionQuoteMenuLabel } from '@/session/selectionQuote';
-import { lineHeight, spacing, useTheme } from '@/theme';
-import { typeScale } from '@/theme/tokens';
+import { lineHeight, useTheme } from '@/theme';
+import { spacing, typeScale } from '@/theme/tokens';
export function MarkdownFileReader({
markdown,
+ onPageSwipe,
onQuoteSelection,
targetLine,
testID,
}: {
markdown: string;
+ /** 由文件预览 pager 消费的明确横向翻页;纵向移动会让该手势失败给 WebView。 */
+ onPageSwipe?: (direction: 'previous' | 'next') => void;
/** chat-text-quote:系统菜单「添加到对话」的采集回调;未传时不加菜单项。 */
onQuoteSelection?: (text: string) => void;
/** 定位到源码行(1-based):加载后滚到覆盖该行的块并闪两下高亮(不驻留)。 */
@@ -50,6 +54,8 @@ export function MarkdownFileReader({
chipColor: colors.surfaceChip,
inlineCodeColor: colors.chatInlineCodeText,
fontSize: typeScale.body,
+ // 与文件预览源码 FlatList 的 codeContent 对齐。
+ horizontalPadding: spacing.lg,
// body(16/22)行高比 1.375,低于 DESIGN.md §3 正文区间 1.43–1.56 下限;
// 文档阅读是长文连续阅读场景,换 bodyRelaxed(16/24)= 1.50 落到规范值。
// 字号不动:16 = DESIGN.md 的 Body 档。
@@ -80,9 +86,18 @@ export function MarkdownFileReader({
if (text && text.trim().length > 0) onQuoteSelectionRef.current?.(text);
}, []);
+ // 文档知道触点是否落在宽公式内;原生外层 Pan 无法区分,会抢走公式横移。
+ // 只接收文档完成的翻页手势,滚动和系统文字选择仍由 WebView 处理。
+ const handleMessage = useCallback((event: { nativeEvent: { data: string } }) => {
+ const direction = parseMarkdownPageSwipe(event.nativeEvent.data);
+ if (direction) onPageSwipe?.(direction);
+ }, [onPageSwipe]);
+
return (
- <View style={styles.content} testID={testID}>
+ <View style={styles.fill} testID={testID}>
<WebView
+ injectedJavaScript={onPageSwipe ? MARKDOWN_FILE_PAGER_SCRIPT : undefined}
+ onMessage={onPageSwipe ? handleMessage : undefined}
menuItems={quoteEnabled ? quoteMenuItems : undefined}
onCustomMenuSelection={quoteEnabled ? handleCustomMenuSelection : undefined}
onShouldStartLoadWithRequest={interceptNavigation}
@@ -107,5 +122,4 @@ function interceptNavigation(request: ShouldStartLoadRequest): boolean {
const styles = StyleSheet.create({
fill: { flex: 1 },
- content: { flex: 1, paddingHorizontal: spacing.lg },
});
diff --git a/apps/mobile/src/session/markdownFilePager.ts b/apps/mobile/src/session/markdownFilePager.ts
new file mode 100644
index 0000000000..081eb3c85e
--- /dev/null
+++ b/apps/mobile/src/session/markdownFilePager.ts
@@ -0,0 +1,80 @@
+export type MarkdownPageDirection = 'previous' | 'next';
+
+export function parseMarkdownPageSwipe(data: string): MarkdownPageDirection | null {
+ if (data === 'markdown-page:previous') return 'previous';
+ if (data === 'markdown-page:next') return 'next';
+ return null;
+}
+
+/**
+ * Classify inside the document, where the touched scroll container is known.
+ * Passive listeners leave vertical scrolling, formula panning and selection native.
+ * The host receives only a completed page swipe, never document content.
+ */
+export const MARKDOWN_FILE_PAGER_SCRIPT = `
+(function () {
+ if (window.__cindyMarkdownPager) return;
+ window.__cindyMarkdownPager = true;
+ var gesture = null;
+ function selected() {
+ var selection = window.getSelection();
+ return selection && !selection.isCollapsed;
+ }
+ function ownsHorizontalPan(target) {
+ var element = target && (target.nodeType === 1 ? target : target.parentElement);
+ while (element && element !== document.body) {
+ if (element.tagName === 'A') return true;
+ var overflow = window.getComputedStyle(element).overflowX;
+ if ((overflow === 'auto' || overflow === 'scroll') &&
+ element.scrollWidth > element.clientWidth + 1) return true;
+ element = element.parentElement;
+ }
+ return false;
+ }
+ function move(touch, time) {
+ if (!gesture || touch.identifier !== gesture.id) return;
+ var dx = touch.clientX - gesture.x;
+ var dy = touch.clientY - gesture.y;
+ if (!gesture.horizontal) {
+ // Once vertical reading or a long press wins, this touch cannot turn into paging.
+ if (Math.abs(dy) > 8 || time - gesture.time > 500) {
+ gesture = null;
+ return;
+ }
+ if (Math.abs(dx) > 16) gesture.horizontal = true;
+ }
+ }
+ document.addEventListener('touchstart', function (event) {
+ gesture = null;
+ if (event.touches.length !== 1 || selected() || ownsHorizontalPan(event.target)) return;
+ var touch = event.touches[0];
+ gesture = { id: touch.identifier, x: touch.clientX, y: touch.clientY,
+ time: event.timeStamp, horizontal: false };
+ }, { passive: true });
+ document.addEventListener('touchmove', function (event) {
+ if (event.touches.length !== 1 || selected()) { gesture = null; return; }
+ move(event.touches[0], event.timeStamp);
+ }, { passive: true });
+ document.addEventListener('touchcancel', function () { gesture = null; }, { passive: true });
+ document.addEventListener('touchend', function (event) {
+ if (!gesture || event.touches.length || event.changedTouches.length !== 1) {
+ gesture = null;
+ return;
+ }
+ var touch = event.changedTouches[0];
+ if (touch.identifier !== gesture.id) { gesture = null; return; }
+ move(touch, event.timeStamp);
+ var ended = gesture;
+ gesture = null;
+ if (!ended || !ended.horizontal || selected()) return;
+ var dx = touch.clientX - ended.x;
+ var dy = touch.clientY - ended.y;
+ var velocity = Math.abs(dx) * 1000 / Math.max(1, event.timeStamp - ended.time);
+ if (Math.abs(dy) > Math.abs(dx) / 2 || (Math.abs(dx) < 56 && velocity < 500)) return;
+ if (window.ReactNativeWebView) {
+ window.ReactNativeWebView.postMessage(dx < 0 ? 'markdown-page:next' : 'markdown-page:previous');
+ }
+ }, { passive: true });
+})();
+true;
+`;
diff --git a/apps/mobile/src/session/selectableMarkdownHtml.ts b/apps/mobile/src/session/selectableMarkdownHtml.ts
index f31a9da1a9..ae6cf8bbe0 100644
--- a/apps/mobile/src/session/selectableMarkdownHtml.ts
+++ b/apps/mobile/src/session/selectableMarkdownHtml.ts
@@ -13,10 +13,10 @@ import { lightColors, lineHeight as lineHeightScale, typeScale } from '@/theme/t
import { i18n } from '@/i18n';
/**
- * 全屏 markdown 文档 HTML 构建器 —— 当前唯一消费方是文件预览的 MarkdownFileReader
- * (WebView 自身滚动的阅读态)。聊天消息气泡已全面切换为原生 markdown 渲染,
+ * 全屏 markdown 文档 HTML 构建器 —— 文件预览的 MarkdownFileReader 使用完整文档
+ * (WebView 自身滚动的阅读态),会话分享复用 CSS 与内容片段。聊天消息气泡已全面切换为原生 markdown 渲染,
* 本模块随之瘦身:气泡专用的 segments 拼装 / bridge 脚本 / 测高估算已删除,
- * 只保留「markdown → 完整 HTML 文档」这一条能力。
+ * 不承担聊天气泡的布局与手势。
*/
export interface SelectableMarkdownHtmlOptions {
/** When supplied, export only these embedded images; never expose source URLs. */
@@ -25,6 +25,8 @@ export interface SelectableMarkdownHtmlOptions {
borderColor?: string;
chipColor?: string;
fontSize?: number;
+ /** 文件预览正文左右边距;调用方传入共享 spacing.lg。 */
+ horizontalPadding?: number;
/** 行内 code 文字色(压暗档,不是底色;见 css 里的说明)。 */
inlineCodeColor?: string;
lineHeight?: number;
@@ -44,6 +46,7 @@ export interface SelectableMarkdownHtmlOptions {
property?: string;
string?: string;
};
+ /** 显式指定时保留列宽并在表内横向滚动(会话分享);省略时按文件预览视口换行。 */
tableCellMinWidth?: number;
textColor?: string;
/**
@@ -187,19 +190,33 @@ export function buildSelectableMarkdownCss(options: SelectableMarkdownHtmlOption
string: cssValue(options.syntaxColors?.string ?? lightColors.syntaxString),
};
const bodyGap = cssNumber(options.bodyGap ?? 10);
+ const horizontalPadding = cssNumber(options.horizontalPadding ?? 16);
const markerWidth = cssNumber(options.markerWidth ?? 24);
- const tableCellMinWidth = cssNumber(options.tableCellMinWidth ?? 112);
+ const tableCellMinWidth = cssNumber(options.tableCellMinWidth ?? 0);
+ // 分享沿用原有的最小列宽;文件阅读器未指定列宽,才启用窄屏等分布局。
+ const tableLayout = options.tableCellMinWidth === undefined
+ ? 'table-layout: fixed; width: 100%;'
+ : 'display: block; max-width: 100%; overflow-x: auto;';
return `
- html, body {
+ html {
margin: 0;
- padding: 0;
+ overflow-x: hidden;
+ overscroll-behavior-x: none;
+ touch-action: auto;
+ }
+ body {
+ box-sizing: border-box;
+ margin: 0;
+ min-width: 0;
+ padding: 0 ${horizontalPadding}px;
background: transparent;
color: ${textColor};
font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", sans-serif;
font-size: ${fontSize}px;
line-height: ${lineHeight}px;
- overflow: visible;
+ overflow-x: hidden;
+ overflow-y: visible;
overflow-wrap: anywhere;
cursor: text;
touch-action: auto;
@@ -215,6 +232,9 @@ export function buildSelectableMarkdownCss(options: SelectableMarkdownHtmlOption
display: flex;
flex-direction: column;
gap: ${bodyGap}px;
+ max-width: 100%;
+ min-width: 0;
+ width: 100%;
-webkit-touch-callout: default !important;
-webkit-user-select: text !important;
user-select: text !important;
@@ -243,6 +263,7 @@ export function buildSelectableMarkdownCss(options: SelectableMarkdownHtmlOption
p, h1, h2, h3, h4, h5, h6, blockquote, pre, table, .list-row {
margin: 0;
}
+ /* 正文横滑切文件;宽公式保留内部横移,文档手势识别器按触点让路。 */
/* 标题分三档。改前 h1–h6 全部等于正文字号(只有 font-weight:500 撑),文档里
完全读不出层级 —— 与聊天消息流同一个缺陷、同一套修法:
h1 20/28 = 1.400(= desktop h1 比例)
@@ -339,7 +360,7 @@ export function buildSelectableMarkdownCss(options: SelectableMarkdownHtmlOption
color: inherit;
text-decoration: underline;
}
- /* 直连图片:本模块的唯一消费方 MarkdownFileReader 没有 postMessage bridge,
+ /* 直连图片:MarkdownFileReader 的 bridge 只接翻页,图片没有点击处理,
生成的 <img> 也不在链接内 —— 点它毫无响应,所以**不带 pointer**(与下面的
.xdt-image-chip 同一条判据:这个面上「像能点」的反馈一律不给)。
上一轮只清了 chip、漏了直连图片这对称的另一半,PR #1144 review 实捉。 */
@@ -380,16 +401,16 @@ export function buildSelectableMarkdownCss(options: SelectableMarkdownHtmlOption
border-left: 1px solid ${borderColor};
border-spacing: 0;
border-top: 1px solid ${borderColor};
- display: block;
- max-width: 100%;
- overflow-x: auto;
+ ${tableLayout}
}
th, td {
border-bottom: 1px solid ${borderColor};
border-right: 1px solid ${borderColor};
box-sizing: border-box;
min-width: ${tableCellMinWidth}px;
+ overflow-wrap: anywhere;
padding: 4px 8px;
+ word-break: break-word;
text-align: left;
vertical-align: top;
}
@@ -397,7 +418,15 @@ export function buildSelectableMarkdownCss(options: SelectableMarkdownHtmlOption
color: ${mutedColor};
font-weight: 500;
}
+ .xdt-math-inline {
+ display: inline-block;
+ max-width: 100%;
+ overflow-x: auto;
+ vertical-align: middle;
+ }
.xdt-math-block {
+ max-width: 100%;
+ min-width: 0;
overflow-x: auto;
text-align: center;
}