merong-docs 0.1.11 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/OVERVIEW.md +19 -19
- package/OVERVIEW.zh-CN.md +19 -22
- package/README.md +77 -77
- package/README.zh-CN.md +81 -81
- package/client/android-file-share.ts +25 -25
- package/client/controls.tsx +163 -163
- package/client/document-panel.tsx +166 -166
- package/client/external-file.tsx +78 -78
- package/client/file-reader.tsx +43 -43
- package/client/markdown-panel.tsx +737 -737
- package/client/markdown-scroll.ts +122 -122
- package/client/messages.ts +224 -224
- package/client/native-contacts.ts +145 -145
- package/client/page-render-queue.ts +12 -12
- package/client/page-selection.tsx +227 -227
- package/client/page-tools.tsx +72 -72
- package/client/pdf-geometry.ts +96 -96
- package/client/pdf-panel.tsx +477 -477
- package/client/reader-find.tsx +190 -190
- package/client/reader-notice.tsx +46 -46
- package/client/settings.tsx +143 -143
- package/client/syntax.tsx +55 -55
- package/client/viewport-geometry.ts +61 -61
- package/client/web.ts +462 -462
- package/client/worksheet-panel.tsx +631 -631
- package/client/zoom-controls.tsx +140 -140
- package/index.client.tsx +36 -36
- package/index.server.ts +73 -73
- package/node_modules/markdown-it/bin/markdown-it.mjs +0 -0
- package/node_modules/yaml/bin.mjs +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/scripts/prepare-office.mjs +20 -20
- package/server/engine.ts +89 -89
- package/server/external-file.ts +42 -42
- package/server/generated/document-worker.ts +1 -1
- package/server/generated/rust-reader_bg.wasm +0 -0
- package/server/markdown-index.ts +305 -305
- package/server/markdown-links.ts +51 -51
- package/server/markdown-page.ts +120 -120
- package/server/office-fonts.cjs +824 -824
- package/server/office-location.ts +41 -41
- package/server/office-preview.ts +186 -186
- package/server/office-worker.cjs +49 -49
- package/server/office-xml.ts +79 -79
- package/server/pdf-engine.ts +168 -168
- package/server/pdf-text-geometry.ts +60 -60
- package/server/rust-reader.ts +40 -40
- package/server/structured-document.ts +69 -69
- package/server/text-search.ts +15 -15
- package/server/worker-entry.ts +42 -42
- package/server/worker-protocol.ts +38 -38
- package/server/worksheet.ts +67 -67
- package/server/workspace-file.ts +63 -63
- package/shared/contracts.ts +187 -187
- package/shared/file-limits.ts +5 -5
- package/shared/markdown-constants.ts +4 -4
- package/shared/markdown-math.ts +198 -198
- package/shared/markdown-references.ts +83 -83
- package/shared/markdown-source-location.ts +8 -8
- package/shared/reader-settings.ts +15 -15
- package/shared/reader-shortcuts.ts +132 -132
- package/vendor/office2pdf/office2pdf_bg.wasm +2 -2
|
@@ -1,737 +1,737 @@
|
|
|
1
|
-
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
|
2
|
-
import { ActivityIndicator, Animated, Dimensions, Easing, Platform, Text, View, useWindowDimensions,
|
|
3
|
-
type FlatList as NativeFlatList, type TextStyle, type ViewStyle } from "react-native";
|
|
4
|
-
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
|
|
5
|
-
import type { RpcInput, RpcOutput } from "@getpaseo/plugin";
|
|
6
|
-
import { useRpc, useTabState, useTranslation, type PluginFilePanelProps } from "@getpaseo/plugin/client";
|
|
7
|
-
import { FlatList, Loading, Markdown, ScrollView } from "@getpaseo/plugin/client/ui";
|
|
8
|
-
import { z } from "zod";
|
|
9
|
-
import { readMarkdownInfo, readMarkdownPage, readMarkdownSource } from "../shared/contracts";
|
|
10
|
-
import { findFormulas, lineOffsets, markdownParser } from "../shared/markdown-math";
|
|
11
|
-
import { inlineReferenceLinks, markdownReferences } from "../shared/markdown-references";
|
|
12
|
-
import { markdownSourceLocation } from "../shared/markdown-source-location";
|
|
13
|
-
import { Control, isTabActive, ReadError, Toolbar, useFileGeneration } from "./controls";
|
|
14
|
-
import { ExternalFileAction } from "./external-file";
|
|
15
|
-
import { bindMarkdownScroll } from "./markdown-scroll";
|
|
16
|
-
import { ReaderFindBar, useMarkdownFind, useReaderFindShortcuts, useReaderFindVisibility, type MarkdownMatch } from "./reader-find";
|
|
17
|
-
import { messages } from "./messages";
|
|
18
|
-
import { Syntax } from "./syntax";
|
|
19
|
-
import { bindMarkdownAnchors, focusReaderFind, observeCodeFont, readerSelection,
|
|
20
|
-
revealMarkdownMatch, webReadingWidth } from "./web";
|
|
21
|
-
|
|
22
|
-
type Page = RpcOutput<typeof readMarkdownPage>;
|
|
23
|
-
type Info = RpcOutput<typeof readMarkdownInfo>;
|
|
24
|
-
type FileTarget = RpcInput<typeof readMarkdownInfo>;
|
|
25
|
-
type PageCursor = Omit<RpcInput<typeof readMarkdownPage>, keyof FileTarget>;
|
|
26
|
-
type LineRange = { first: number; last: number };
|
|
27
|
-
type PreviewBlock = { key: string; first: number; last: number; text: string };
|
|
28
|
-
const markdownTabState = z.object({ mode: z.enum(["source", "preview", "split"]).nullable() });
|
|
29
|
-
type Mode = NonNullable<z.infer<typeof markdownTabState>["mode"]>;
|
|
30
|
-
type SourceRow = RpcOutput<typeof readMarkdownSource>["lines"][number] & { number: number };
|
|
31
|
-
type SourcePosition = { first: number; count: number };
|
|
32
|
-
type SourceJump = { line: number; center: boolean; offset?: number };
|
|
33
|
-
type PreviewJump = { line: number; index?: number; find?: boolean };
|
|
34
|
-
type SplitPane = "preview" | "source";
|
|
35
|
-
const defaultCodeSize = 12;
|
|
36
|
-
const wideSplitWidth = 680;
|
|
37
|
-
const contentFrame = { width: "100%", alignSelf: "center", paddingHorizontal: 8 } as const;
|
|
38
|
-
const nativeReadingWidth = { maxWidth: 820 };
|
|
39
|
-
const cachedBlocks = new WeakMap<Page, { info?: Info; blocks: PreviewBlock[] }>();
|
|
40
|
-
const webGutter = { position: "sticky", left: 0, zIndex: 1 } as unknown as ViewStyle;
|
|
41
|
-
const fixedSourceScroll = { overflowAnchor: "none" } as unknown as ViewStyle;
|
|
42
|
-
const preformatted = { whiteSpace: "pre", tabSize: 4 } as TextStyle;
|
|
43
|
-
const wrappedSource = { whiteSpace: "pre-wrap", overflowWrap: "anywhere", tabSize: 4 } as TextStyle;
|
|
44
|
-
const hiddenOnWeb = { visibility: "hidden" } as unknown as ViewStyle;
|
|
45
|
-
const sourceProbeText = "```\n00000000\n00000000\n```";
|
|
46
|
-
|
|
47
|
-
function SourceScroll({ wrap, width, children }: { wrap: boolean; width: number; children: ReactNode }) {
|
|
48
|
-
if (wrap) return children;
|
|
49
|
-
return <ScrollView horizontal nestedScrollEnabled directionalLockEnabled style={{ flex: 1 }}
|
|
50
|
-
contentContainerStyle={{ minWidth: "100%", width: Math.max(180, width), flexGrow: 1 }}>{children}</ScrollView>;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function previewBlocks(page: Page, info?: Info): PreviewBlock[] {
|
|
54
|
-
const cached = cachedBlocks.get(page);
|
|
55
|
-
if (cached && cached.info === info) return cached.blocks;
|
|
56
|
-
const metadataLines = info?.revision === page.revision && page.prefixLines === 0
|
|
57
|
-
? Math.max(0, info.frontMatterEnd - page.firstLine + 1) : 0;
|
|
58
|
-
const source = metadataLines ? page.markdown.slice(lineOffsets(page.markdown)[metadataLines] ?? page.markdown.length) : page.markdown;
|
|
59
|
-
if (!source.trim()) {
|
|
60
|
-
cachedBlocks.set(page, { info, blocks: [] });
|
|
61
|
-
return [];
|
|
62
|
-
}
|
|
63
|
-
const references = info?.revision === page.revision ? info.references : markdownReferences(source);
|
|
64
|
-
const offsets = lineOffsets(source);
|
|
65
|
-
const formulas = findFormulas(source).filter((span) => span.block);
|
|
66
|
-
const starts = markdownParser.parse(source, {}).filter((token) => token.level === 0 && token.map)
|
|
67
|
-
.map((token) => token.map![0]);
|
|
68
|
-
const boundaries = [...new Set([0, ...starts, offsets.length - 1])].filter((line) =>
|
|
69
|
-
!formulas.some((span) => span.start < offsets[line] && offsets[line] < span.end));
|
|
70
|
-
const blocks: PreviewBlock[] = [];
|
|
71
|
-
const sourceBase = page.firstLine + metadataLines - page.prefixLines;
|
|
72
|
-
const lastSource = page.nextLine - Number(/(?:\r\n|\r|\n)$/.test(page.source));
|
|
73
|
-
for (const [index, line] of boundaries.slice(0, -1).entries()) {
|
|
74
|
-
const next = boundaries[index + 1];
|
|
75
|
-
const block = source.slice(offsets[line], offsets[next]).trimEnd();
|
|
76
|
-
if (!block || (block.trimStart().startsWith("[") && !markdownParser.parse(block, {}).length)) continue;
|
|
77
|
-
const first = Math.max(page.firstLine + metadataLines, sourceBase + line);
|
|
78
|
-
const last = Math.max(first, Math.min(lastSource, sourceBase + line + block.split(/\r\n|\r|\n/).length - 1));
|
|
79
|
-
blocks.push({ key: `${page.offset}:${index}`, first, last, text: inlineReferenceLinks(block, references) });
|
|
80
|
-
}
|
|
81
|
-
cachedBlocks.set(page, { info, blocks });
|
|
82
|
-
return blocks;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function Metadata({ info, theme }: { info: Info; theme: PluginFilePanelProps["theme"] }) {
|
|
86
|
-
return (
|
|
87
|
-
<View style={{ backgroundColor: theme.colors.surface1, borderColor: theme.colors.border, borderWidth: 1,
|
|
88
|
-
borderRadius: 8, padding: 12, gap: 6 }}>
|
|
89
|
-
{info.frontMatter.map(({ key, value }) => (
|
|
90
|
-
<View key={key} style={{ flexDirection: "row", gap: 12 }}>
|
|
91
|
-
<Text selectable style={{ flex: 1, color: theme.colors.foregroundMuted, fontWeight: "600" }}>{key}</Text>
|
|
92
|
-
<Text selectable style={{ flex: 2, color: theme.colors.foreground }}>{value}</Text>
|
|
93
|
-
</View>
|
|
94
|
-
))}
|
|
95
|
-
</View>
|
|
96
|
-
);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
function MatchText({ text, matches, active, theme }: {
|
|
100
|
-
text: string; matches: MarkdownMatch[]; active?: MarkdownMatch; theme: PluginFilePanelProps["theme"];
|
|
101
|
-
}) {
|
|
102
|
-
let offset = 0;
|
|
103
|
-
const parts = matches.map((match) => {
|
|
104
|
-
const preceding = text.slice(offset, match.column);
|
|
105
|
-
offset = Math.min(text.length, match.column + match.length);
|
|
106
|
-
if (match.column > text.length) return preceding;
|
|
107
|
-
const selected = match === active;
|
|
108
|
-
return (
|
|
109
|
-
<Text key={match.column}>
|
|
110
|
-
{preceding}<Text {...(selected ? { dataSet: { activeMatch: "true" } } : {})} style={{
|
|
111
|
-
backgroundColor: selected ? theme.colors.accent : theme.colors.surface2,
|
|
112
|
-
color: selected ? theme.colors.accentForeground : theme.colors.foreground,
|
|
113
|
-
...(match.length === 0 ? { borderLeftWidth: 2, borderColor: theme.colors.accent } : {}),
|
|
114
|
-
}}>{text.slice(match.column, offset) || "\u200B"}</Text>
|
|
115
|
-
</Text>
|
|
116
|
-
);
|
|
117
|
-
});
|
|
118
|
-
return <>{parts}{text.slice(offset)}</>;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
export function MarkdownPanel(props: PluginFilePanelProps) {
|
|
122
|
-
const { file, workspaceId, host, theme, params, revision, layout: { compact, platform } } = props;
|
|
123
|
-
const generation = useFileGeneration(file);
|
|
124
|
-
const { t } = useTranslation(messages);
|
|
125
|
-
const web = platform === "web";
|
|
126
|
-
const tabActive = isTabActive(props.tab);
|
|
127
|
-
const read = useRpc(readMarkdownPage);
|
|
128
|
-
const readInfo = useRpc(readMarkdownInfo);
|
|
129
|
-
const readSource = useRpc(readMarkdownSource);
|
|
130
|
-
const target = useMemo<FileTarget>(() => ({ workspaceId, path: file.path }), [workspaceId, file.path]);
|
|
131
|
-
const [attempt, setAttempt] = useState(0);
|
|
132
|
-
const [panelWidth, setPanelWidth] = useState(0);
|
|
133
|
-
const screen = Dimensions.get("screen");
|
|
134
|
-
const desktopLayout = web || (Platform.OS === "ios" && Platform.isPad)
|
|
135
|
-
|| Math.min(screen.width, screen.height) >= 600;
|
|
136
|
-
const sideBySide = desktopLayout && panelWidth >= wideSplitWidth;
|
|
137
|
-
const defaultMode = sideBySide ? "split" : "preview";
|
|
138
|
-
const [savedView, setTabState] = useTabState(props.tab, markdownTabState, { mode: null });
|
|
139
|
-
const [selectedMode, setMode] = useState(savedView.mode);
|
|
140
|
-
const requestedLine = markdownSourceLocation(params.lineStart)?.first;
|
|
141
|
-
const mode = selectedMode ?? (requestedLine ? "source" : defaultMode);
|
|
142
|
-
const split = mode === "split";
|
|
143
|
-
useEffect(() => {
|
|
144
|
-
if (sideBySide && selectedMode === null && !requestedLine) {
|
|
145
|
-
setMode("split");
|
|
146
|
-
setTabState({ mode: "split" });
|
|
147
|
-
}
|
|
148
|
-
}, [requestedLine, selectedMode, setTabState, sideBySide]);
|
|
149
|
-
const previewVisible = mode !== "source";
|
|
150
|
-
const sourceVisible = mode === "source" || split;
|
|
151
|
-
const [visited, setVisited] = useState({ preview: !requestedLine, source: !!requestedLine });
|
|
152
|
-
useEffect(() => {
|
|
153
|
-
setVisited((current) => {
|
|
154
|
-
const preview = current.preview || previewVisible;
|
|
155
|
-
const source = current.source || sourceVisible;
|
|
156
|
-
return preview === current.preview && source === current.source ? current : { preview, source };
|
|
157
|
-
});
|
|
158
|
-
}, [previewVisible, sourceVisible]);
|
|
159
|
-
const hasPreview = visited.preview || previewVisible;
|
|
160
|
-
const hasSource = visited.source || sourceVisible;
|
|
161
|
-
const [targetLine, setTargetLine] = useState(1);
|
|
162
|
-
const [sourceLine, setSourceLine] = useState(requestedLine ?? 1);
|
|
163
|
-
const [flash, setFlash] = useState<LineRange | undefined>();
|
|
164
|
-
const [sourceJump, setSourceJump] = useState<SourceJump>();
|
|
165
|
-
const [flashOpacity] = useState(() => new Animated.Value(0));
|
|
166
|
-
const { findOpen, showFind, hideFind } = useReaderFindVisibility();
|
|
167
|
-
const defaultFamily = platform === "ios" ? "ui-monospace" : "monospace";
|
|
168
|
-
const [codeFont, setCodeFont] = useState({ size: defaultCodeSize, family: defaultFamily, digitWidth: defaultCodeSize * 0.62 });
|
|
169
|
-
const visibleLine = useRef(1);
|
|
170
|
-
const visibleSource = useRef(requestedLine ?? 1);
|
|
171
|
-
const previewOffset = useRef(0);
|
|
172
|
-
const sourceOffset = useRef(0);
|
|
173
|
-
const sourceHeight = useRef(0);
|
|
174
|
-
const nativeSplitDriver = useRef<SplitPane>(undefined);
|
|
175
|
-
const beforeFind = useRef<{ version: string; mode: Mode; sourceLine: number; sourceOffset: number;
|
|
176
|
-
targetLine: number; previewOffset: number }>(undefined);
|
|
177
|
-
const restorePreview = useRef<{ line: number; offset: number }>(undefined);
|
|
178
|
-
const nativePreviewJump = useRef<number>(undefined);
|
|
179
|
-
const previewHeaderHeight = useRef(0);
|
|
180
|
-
const currentBlock = useRef<PreviewBlock>(undefined);
|
|
181
|
-
const panelRoot = useRef<View>(null);
|
|
182
|
-
const previewRoot = useRef<View>(null);
|
|
183
|
-
const sourceRoot = useRef<View>(null);
|
|
184
|
-
const codeProbe = useRef<View>(null);
|
|
185
|
-
const previewList = useRef<NativeFlatList<PreviewBlock>>(null);
|
|
186
|
-
const sourceList = useRef<NativeFlatList<SourceRow>>(null);
|
|
187
|
-
const sourceWindow = useRef<SourcePosition>({ first: 1, count: 0 });
|
|
188
|
-
const webScroll = useRef<ReturnType<typeof bindMarkdownScroll>>(undefined);
|
|
189
|
-
const pendingPreview = useRef<PreviewJump>(undefined);
|
|
190
|
-
const placePreview = useRef<(line: number) => void>(undefined);
|
|
191
|
-
const previewFrame = useRef<number>(undefined);
|
|
192
|
-
const scrollRetryTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
|
|
193
|
-
const scrollTries = useRef(0);
|
|
194
|
-
const completedJump = useRef<SourceJump>(undefined);
|
|
195
|
-
const version = `${file.modifiedAt}:${generation}:${attempt}`;
|
|
196
|
-
const fileKey = ["merong-docs", "markdown", host.id, workspaceId, file.path, version] as const;
|
|
197
|
-
const find = useMarkdownFind(target, fileKey, tabActive && findOpen);
|
|
198
|
-
const versionRef = useRef(version);
|
|
199
|
-
if (versionRef.current !== version) {
|
|
200
|
-
versionRef.current = version;
|
|
201
|
-
setTargetLine(visibleLine.current);
|
|
202
|
-
setSourceLine(visibleSource.current);
|
|
203
|
-
}
|
|
204
|
-
const changeMode = useCallback((next: Mode) => {
|
|
205
|
-
nativeSplitDriver.current = undefined;
|
|
206
|
-
if (next !== selectedMode) {
|
|
207
|
-
setMode(next);
|
|
208
|
-
setTabState({ mode: next });
|
|
209
|
-
}
|
|
210
|
-
}, [selectedMode, setTabState]);
|
|
211
|
-
const jumpToSource = useCallback((line: number, center = false) => {
|
|
212
|
-
clearTimeout(scrollRetryTimer.current);
|
|
213
|
-
const { first, count } = sourceWindow.current;
|
|
214
|
-
if (line < first || line >= first + count) setSourceLine(Math.max(1, line - (center ? 24 : 0)));
|
|
215
|
-
setSourceJump({ line, center });
|
|
216
|
-
visibleSource.current = line;
|
|
217
|
-
}, []);
|
|
218
|
-
const showPreview = useCallback((line: number) => {
|
|
219
|
-
nativeSplitDriver.current = undefined;
|
|
220
|
-
visibleLine.current = line;
|
|
221
|
-
if (web && previewVisible && placePreview.current) {
|
|
222
|
-
placePreview.current(line);
|
|
223
|
-
} else {
|
|
224
|
-
previewOffset.current = 0;
|
|
225
|
-
setTargetLine(line);
|
|
226
|
-
}
|
|
227
|
-
beforeFind.current = undefined;
|
|
228
|
-
if (findOpen) hideFind();
|
|
229
|
-
if (split) jumpToSource(line);
|
|
230
|
-
}, [findOpen, hideFind, jumpToSource, previewVisible, split, web]);
|
|
231
|
-
const infoQuery = useQuery({
|
|
232
|
-
queryKey: [...fileKey, "info"], queryFn: () => readInfo(target), staleTime: Infinity, gcTime: 30_000, retry: false,
|
|
233
|
-
});
|
|
234
|
-
const info = infoQuery.data;
|
|
235
|
-
const linkRange = markdownSourceLocation(params.lineStart, params.lineEnd, info?.lineCount);
|
|
236
|
-
const linkStart = linkRange?.first;
|
|
237
|
-
const handledLocation = useRef<{ line: number; revision: number }>(undefined);
|
|
238
|
-
useEffect(() => {
|
|
239
|
-
if (!linkStart) {
|
|
240
|
-
handledLocation.current = undefined;
|
|
241
|
-
return;
|
|
242
|
-
}
|
|
243
|
-
if (handledLocation.current?.line === linkStart && handledLocation.current.revision === revision) return;
|
|
244
|
-
handledLocation.current = { line: linkStart, revision };
|
|
245
|
-
beforeFind.current = undefined;
|
|
246
|
-
if (findOpen) hideFind();
|
|
247
|
-
if (pendingPreview.current?.find) pendingPreview.current = undefined;
|
|
248
|
-
nativePreviewJump.current = undefined;
|
|
249
|
-
changeMode("source");
|
|
250
|
-
jumpToSource(linkStart, true);
|
|
251
|
-
}, [linkStart, revision, changeMode, findOpen, hideFind, jumpToSource]);
|
|
252
|
-
useEffect(() => () => {
|
|
253
|
-
clearTimeout(scrollRetryTimer.current);
|
|
254
|
-
if (previewFrame.current !== undefined) cancelAnimationFrame(previewFrame.current);
|
|
255
|
-
}, []);
|
|
256
|
-
useEffect(() => {
|
|
257
|
-
if (!web) return;
|
|
258
|
-
return observeCodeFont(codeProbe.current, (size, family, digitWidth) => {
|
|
259
|
-
const resolvedFamily = family || defaultFamily;
|
|
260
|
-
setCodeFont((prior) => prior.size === size && prior.family === resolvedFamily && prior.digitWidth === digitWidth
|
|
261
|
-
? prior : { size, family: resolvedFamily, digitWidth });
|
|
262
|
-
});
|
|
263
|
-
}, [web, defaultFamily]);
|
|
264
|
-
|
|
265
|
-
const preview = useInfiniteQuery({
|
|
266
|
-
queryKey: [...fileKey, "preview", targetLine],
|
|
267
|
-
queryFn: ({ pageParam }) => read({ ...target, ...pageParam }),
|
|
268
|
-
initialPageParam: { offset: 0, atLine: targetLine > 1 ? targetLine : undefined } as PageCursor,
|
|
269
|
-
getNextPageParam: ({ nextOffset, nextLine, revision, fence, table }): PageCursor | undefined => nextOffset === null ? undefined
|
|
270
|
-
: { offset: nextOffset, firstLine: nextLine, revision, fence, table },
|
|
271
|
-
enabled: hasPreview, staleTime: Infinity, gcTime: 30_000, retry: false,
|
|
272
|
-
});
|
|
273
|
-
const source = useInfiniteQuery({
|
|
274
|
-
queryKey: [...fileKey, "source", sourceLine],
|
|
275
|
-
queryFn: ({ pageParam }) => readSource({ ...target, line: pageParam }),
|
|
276
|
-
initialPageParam: sourceLine,
|
|
277
|
-
getNextPageParam: (page) => page.nextLine ?? undefined,
|
|
278
|
-
enabled: hasSource, staleTime: Infinity, gcTime: 30_000, retry: false,
|
|
279
|
-
});
|
|
280
|
-
const anchors = useMemo(() => new Map(info?.headings.filter(({ anchor }) => anchor).map(({ anchor, line }) =>
|
|
281
|
-
[`#${encodeURIComponent(anchor)}`, () => showPreview(line)])), [info, showPreview]);
|
|
282
|
-
const anchorsRef = useRef(anchors);
|
|
283
|
-
anchorsRef.current = anchors;
|
|
284
|
-
useEffect(() => {
|
|
285
|
-
if (!web || !hasPreview) return;
|
|
286
|
-
return bindMarkdownAnchors(previewRoot.current, (href) => {
|
|
287
|
-
let key = href;
|
|
288
|
-
try { key = `#${encodeURIComponent(decodeURIComponent(href.slice(1)))}`; } catch { return false; }
|
|
289
|
-
const action = anchorsRef.current.get(key);
|
|
290
|
-
action?.();
|
|
291
|
-
return !!action;
|
|
292
|
-
});
|
|
293
|
-
}, [web, hasPreview]);
|
|
294
|
-
|
|
295
|
-
const blocks = useMemo(() => preview.data?.pages.flatMap((page, index) => {
|
|
296
|
-
const pageBlocks = previewBlocks(page, info);
|
|
297
|
-
return index > 0 ? pageBlocks : pageBlocks.filter((block) => block.last >= targetLine);
|
|
298
|
-
}) ?? [], [info, preview.data, targetLine]);
|
|
299
|
-
const sourceRows = useMemo(() => source.data?.pages.flatMap((page) => page.lines.map((line, index) =>
|
|
300
|
-
({ ...line, number: page.firstLine + index }))) ?? [], [source.data]);
|
|
301
|
-
const firstSource = sourceRows[0]?.number ?? sourceLine;
|
|
302
|
-
sourceWindow.current = { first: firstSource, count: sourceRows.length };
|
|
303
|
-
const flashLoaded = !!flash && flash.first >= firstSource && flash.first < firstSource + sourceRows.length;
|
|
304
|
-
useEffect(() => {
|
|
305
|
-
if (!sourceVisible || !flashLoaded) return;
|
|
306
|
-
const flashFrame = requestAnimationFrame(() => {
|
|
307
|
-
flashOpacity.setValue(0.24);
|
|
308
|
-
Animated.timing(flashOpacity, {
|
|
309
|
-
toValue: 0, duration: 920, delay: 130, easing: Easing.out(Easing.quad), useNativeDriver: !web,
|
|
310
|
-
}).start(({ finished }) => {
|
|
311
|
-
if (finished) setFlash((current) => current === flash ? undefined : current);
|
|
312
|
-
});
|
|
313
|
-
});
|
|
314
|
-
return () => {
|
|
315
|
-
cancelAnimationFrame(flashFrame);
|
|
316
|
-
flashOpacity.stopAnimation();
|
|
317
|
-
};
|
|
318
|
-
}, [flash, flashLoaded, flashOpacity, sourceVisible, web]);
|
|
319
|
-
const dimensions = useWindowDimensions();
|
|
320
|
-
const fontScale = web ? 1 : dimensions.fontScale;
|
|
321
|
-
const sourceFontSize = codeFont.size * fontScale;
|
|
322
|
-
const rowHeight = sourceFontSize * 1.45;
|
|
323
|
-
const codeStyle = { fontFamily: codeFont.family, fontSize: sourceFontSize, lineHeight: rowHeight, includeFontPadding: false } as const;
|
|
324
|
-
const wrapSource = mode === "source" && (!web || /\.(?:md|markdown)$/i.test(file.name) && file.size <= 1024 * 1024);
|
|
325
|
-
const sourceTop = web ? 16 : 0;
|
|
326
|
-
const sourcePixel = (line: number) => sourceTop + (line - firstSource) * rowHeight;
|
|
327
|
-
const showBlockSource = (range: LineRange) => {
|
|
328
|
-
changeMode(split || sideBySide ? "split" : "source");
|
|
329
|
-
const viewport = split ? web ? webScroll.current?.sourceViewport() : { top: sourceOffset.current, height: sourceHeight.current } : undefined;
|
|
330
|
-
const first = sourcePixel(range.first);
|
|
331
|
-
const end = sourcePixel(range.last + 1);
|
|
332
|
-
const shown = viewport && range.first >= firstSource && range.first < firstSource + sourceRows.length
|
|
333
|
-
&& first >= viewport.top - 1
|
|
334
|
-
&& (end - first > viewport.height ? first + rowHeight : end) <= viewport.top + viewport.height + 1;
|
|
335
|
-
if (!shown) jumpToSource(range.first, true);
|
|
336
|
-
setFlash({ ...range });
|
|
337
|
-
};
|
|
338
|
-
const gutterWidth = web ? Math.max(21, Math.ceil(String(info?.lineCount ?? sourceRows.at(-1)?.number ?? 1).length * codeFont.digitWidth + 9))
|
|
339
|
-
: Math.max(56, String(info?.lineCount ?? sourceRows.at(-1)?.number ?? 1).length * sourceFontSize * 0.62 + 15);
|
|
340
|
-
const sourceWidth = useMemo(() => wrapSource ? 0 : Math.min(26_000, sourceRows.reduce((width, { text }) => {
|
|
341
|
-
const length = text.length + (text.match(/[\u2e80-\uffef\t]/g)?.length ?? 0) * 2;
|
|
342
|
-
return Math.max(width, gutterWidth + 19 + length * sourceFontSize * 0.67);
|
|
343
|
-
}, 0)), [gutterWidth, sourceFontSize, sourceRows, wrapSource]);
|
|
344
|
-
const hitsByLine = useMemo(() => {
|
|
345
|
-
const groups = new Map<number, MarkdownMatch[]>();
|
|
346
|
-
for (const hit of find.hits) {
|
|
347
|
-
const group = groups.get(hit.line);
|
|
348
|
-
if (group) group.push(hit);
|
|
349
|
-
else groups.set(hit.line, [hit]);
|
|
350
|
-
}
|
|
351
|
-
return groups;
|
|
352
|
-
}, [find.hits]);
|
|
353
|
-
const openFind = () => {
|
|
354
|
-
if (findOpen) return focusReaderFind(panelRoot.current, "merong-markdown-find");
|
|
355
|
-
if (!web) beforeFind.current = {
|
|
356
|
-
version, mode, sourceLine, sourceOffset: sourceOffset.current, targetLine, previewOffset: previewOffset.current,
|
|
357
|
-
};
|
|
358
|
-
const selected = web ? readerSelection(panelRoot.current) : "";
|
|
359
|
-
if (selected && !selected.includes("\n")) find.changeQuery(selected.slice(0, 256));
|
|
360
|
-
showFind();
|
|
361
|
-
};
|
|
362
|
-
const closeFind = () => {
|
|
363
|
-
hideFind();
|
|
364
|
-
const saved = beforeFind.current;
|
|
365
|
-
beforeFind.current = undefined;
|
|
366
|
-
nativePreviewJump.current = undefined;
|
|
367
|
-
if (pendingPreview.current?.find) pendingPreview.current = undefined;
|
|
368
|
-
if (saved?.version !== version) return;
|
|
369
|
-
clearTimeout(scrollRetryTimer.current);
|
|
370
|
-
changeMode(saved.mode);
|
|
371
|
-
if (saved.mode !== "preview") {
|
|
372
|
-
setSourceLine(saved.sourceLine);
|
|
373
|
-
setSourceJump({ line: saved.sourceLine, center: false, offset: saved.sourceOffset });
|
|
374
|
-
}
|
|
375
|
-
if (saved.mode === "source") return;
|
|
376
|
-
if (targetLine !== saved.targetLine) {
|
|
377
|
-
restorePreview.current = { line: saved.targetLine, offset: saved.previewOffset };
|
|
378
|
-
setTargetLine(saved.targetLine);
|
|
379
|
-
} else if (previewOffset.current !== saved.previewOffset) {
|
|
380
|
-
previewList.current?.scrollToOffset({ offset: saved.previewOffset, animated: false });
|
|
381
|
-
}
|
|
382
|
-
};
|
|
383
|
-
useReaderFindShortcuts(panelRoot, "merong-markdown-find", web && tabActive,
|
|
384
|
-
{ open: openFind, close: closeFind, move: find.move, isOpen: () => findOpen });
|
|
385
|
-
useEffect(() => {
|
|
386
|
-
if (!sourceVisible || !sourceJump || sourceJump === completedJump.current ||
|
|
387
|
-
sourceJump.line < firstSource || sourceJump.line >= firstSource + sourceRows.length) return;
|
|
388
|
-
const frame = requestAnimationFrame(() => {
|
|
389
|
-
const list = sourceList.current;
|
|
390
|
-
if (!list) return;
|
|
391
|
-
completedJump.current = sourceJump;
|
|
392
|
-
scrollTries.current = 0;
|
|
393
|
-
const offset = sourceTop + (sourceJump.line - firstSource) * rowHeight;
|
|
394
|
-
const scroller = split ? webScroll.current : undefined;
|
|
395
|
-
const viewport = scroller?.sourceViewport();
|
|
396
|
-
if (viewport && scroller?.scrollSource(sourceJump.center
|
|
397
|
-
? offset - (viewport.height - rowHeight) * 0.35 : sourceJump.offset ?? offset)) return;
|
|
398
|
-
if (sourceJump.center) {
|
|
399
|
-
list.scrollToIndex({ index: sourceJump.line - firstSource, viewPosition: 0.35, animated: false });
|
|
400
|
-
} else {
|
|
401
|
-
list.scrollToOffset({ offset: sourceJump.offset ?? Math.max(0, sourceJump.line - firstSource) * rowHeight, animated: false });
|
|
402
|
-
}
|
|
403
|
-
});
|
|
404
|
-
return () => cancelAnimationFrame(frame);
|
|
405
|
-
}, [firstSource, rowHeight, sourceJump, sourceRows.length, sourceTop, sourceVisible, split]);
|
|
406
|
-
const recoverSourceScroll = ({ index, averageItemLength }: { index: number; averageItemLength: number }) => {
|
|
407
|
-
if (scrollTries.current++ >= 3) return;
|
|
408
|
-
const list = sourceList.current;
|
|
409
|
-
list?.scrollToOffset({ offset: index * (averageItemLength || rowHeight), animated: false });
|
|
410
|
-
scrollRetryTimer.current = setTimeout(() => {
|
|
411
|
-
if (list && list === sourceList.current) list.scrollToIndex({ index, viewPosition: 0.35, animated: false });
|
|
412
|
-
}, 70);
|
|
413
|
-
};
|
|
414
|
-
useEffect(() => {
|
|
415
|
-
if (!web || !find.active || sourceJump?.line !== find.active.line || !sourceVisible ||
|
|
416
|
-
find.active.line < firstSource || find.active.line >= firstSource + sourceRows.length) return;
|
|
417
|
-
const timeout = setTimeout(() => revealMarkdownMatch(sourceRoot.current), 100);
|
|
418
|
-
return () => clearTimeout(timeout);
|
|
419
|
-
}, [find.active, firstSource, sourceJump, sourceRows.length, sourceVisible, web]);
|
|
420
|
-
const alignPreview = useRef<() => void>(undefined);
|
|
421
|
-
alignPreview.current = () => {
|
|
422
|
-
const pending = pendingPreview.current;
|
|
423
|
-
const scroller = webScroll.current;
|
|
424
|
-
if (!pending || !scroller || preview.isPending) return;
|
|
425
|
-
if (scroller.scrollPreview(pending.line, pending.find)) {
|
|
426
|
-
pendingPreview.current = undefined;
|
|
427
|
-
visibleLine.current = Math.floor(pending.line);
|
|
428
|
-
return;
|
|
429
|
-
}
|
|
430
|
-
const last = blocks.at(-1);
|
|
431
|
-
if (pending.line < targetLine || last && pending.line > last.last + 1 && preview.hasNextPage) {
|
|
432
|
-
if (preview.isFetching) return;
|
|
433
|
-
if (pending.line >= targetLine && last && pending.line < last.last + 128) {
|
|
434
|
-
void preview.fetchNextPage({ cancelRefetch: false });
|
|
435
|
-
} else {
|
|
436
|
-
setTargetLine(Math.max(1, Math.floor(pending.line)));
|
|
437
|
-
}
|
|
438
|
-
return;
|
|
439
|
-
}
|
|
440
|
-
if (!last || pending.line > last.last + 1) {
|
|
441
|
-
scroller.scrollPreviewToEnd();
|
|
442
|
-
pendingPreview.current = undefined;
|
|
443
|
-
return;
|
|
444
|
-
}
|
|
445
|
-
const next = blocks.findIndex((block) => block.first > pending.line);
|
|
446
|
-
const index = Math.max(0, (next < 0 ? blocks.length : next) - 1);
|
|
447
|
-
if (index === pending.index || !previewList.current) return;
|
|
448
|
-
pending.index = index;
|
|
449
|
-
previewList.current.scrollToIndex({ index, animated: false });
|
|
450
|
-
};
|
|
451
|
-
placePreview.current = (line) => {
|
|
452
|
-
pendingPreview.current = { line, index: pendingPreview.current?.index };
|
|
453
|
-
alignPreview.current?.();
|
|
454
|
-
};
|
|
455
|
-
const schedulePreviewAlignment = useCallback(() => {
|
|
456
|
-
if (!pendingPreview.current || previewFrame.current !== undefined) return;
|
|
457
|
-
previewFrame.current = requestAnimationFrame(() => {
|
|
458
|
-
previewFrame.current = undefined;
|
|
459
|
-
alignPreview.current?.();
|
|
460
|
-
});
|
|
461
|
-
}, []);
|
|
462
|
-
useEffect(() => {
|
|
463
|
-
schedulePreviewAlignment();
|
|
464
|
-
}, [blocks, preview.isFetching, schedulePreviewAlignment, targetLine]);
|
|
465
|
-
|
|
466
|
-
const jumpToNativePreview = (line: number, viewPosition: number) => {
|
|
467
|
-
if (line <= (info?.frontMatterEnd ?? 0)) {
|
|
468
|
-
if (targetLine === 1) previewList.current?.scrollToOffset({ offset: 0, animated: false });
|
|
469
|
-
else setTargetLine(1);
|
|
470
|
-
return;
|
|
471
|
-
}
|
|
472
|
-
const next = blocks.findIndex(({ first }) => first > line);
|
|
473
|
-
const index = next < 0 ? blocks.length - 1 : Math.max(0, next - 1);
|
|
474
|
-
const last = blocks.at(-1);
|
|
475
|
-
if (!last || line < targetLine || (line > last.last && preview.hasNextPage) || !previewList.current) {
|
|
476
|
-
if (!viewPosition && preview.isPending) return;
|
|
477
|
-
if (targetLine !== line) setTargetLine(line);
|
|
478
|
-
return;
|
|
479
|
-
}
|
|
480
|
-
if (!viewPosition && blocks[index] === currentBlock.current && previewOffset.current > previewHeaderHeight.current + 1) return;
|
|
481
|
-
nativePreviewJump.current = line;
|
|
482
|
-
previewList.current.scrollToIndex({ index, viewPosition, animated: false });
|
|
483
|
-
nativePreviewJump.current = undefined;
|
|
484
|
-
};
|
|
485
|
-
const navigateToMatch = useRef<(match: MarkdownMatch) => void>(undefined);
|
|
486
|
-
navigateToMatch.current = (match) => {
|
|
487
|
-
nativeSplitDriver.current = undefined;
|
|
488
|
-
if (sourceVisible) jumpToSource(match.line, true);
|
|
489
|
-
if (!previewVisible) return;
|
|
490
|
-
if (web) {
|
|
491
|
-
pendingPreview.current = { line: match.line, find: true };
|
|
492
|
-
schedulePreviewAlignment();
|
|
493
|
-
} else {
|
|
494
|
-
jumpToNativePreview(match.line, 0.25);
|
|
495
|
-
}
|
|
496
|
-
};
|
|
497
|
-
useEffect(() => {
|
|
498
|
-
if (find.active) navigateToMatch.current?.(find.active);
|
|
499
|
-
else {
|
|
500
|
-
nativePreviewJump.current = undefined;
|
|
501
|
-
if (pendingPreview.current?.find) pendingPreview.current = undefined;
|
|
502
|
-
}
|
|
503
|
-
}, [find.active, previewVisible, sourceVisible]);
|
|
504
|
-
const restorePreviewPosition = () => {
|
|
505
|
-
const restore = restorePreview.current;
|
|
506
|
-
if (!restore || restore.line !== targetLine || !previewList.current) return;
|
|
507
|
-
restorePreview.current = undefined;
|
|
508
|
-
previewList.current.scrollToOffset({ offset: restore.offset, animated: false });
|
|
509
|
-
};
|
|
510
|
-
const previewMatchMarker = (first: number, last: number) => {
|
|
511
|
-
const line = find.active?.line;
|
|
512
|
-
return previewVisible && line !== undefined && line >= first && line <= last
|
|
513
|
-
? <View testID="merong-markdown-preview-match" pointerEvents="none" style={{ position: "absolute",
|
|
514
|
-
left: 1, top: 0, bottom: 0, width: 2, borderRadius: 1, backgroundColor: theme.colors.accent }} />
|
|
515
|
-
: null;
|
|
516
|
-
};
|
|
517
|
-
|
|
518
|
-
const scrollActions = useRef<Parameters<typeof bindMarkdownScroll>[1]>(undefined);
|
|
519
|
-
scrollActions.current = {
|
|
520
|
-
previewStart: () => targetLine,
|
|
521
|
-
preview: (line) => {
|
|
522
|
-
if (pendingPreview.current) return schedulePreviewAlignment();
|
|
523
|
-
if (!previewVisible || line === undefined) return;
|
|
524
|
-
visibleLine.current = Math.floor(line);
|
|
525
|
-
if (!split) return;
|
|
526
|
-
if (line < firstSource || line >= firstSource + sourceRows.length) {
|
|
527
|
-
if (Math.floor(line) !== sourceJump?.line) jumpToSource(Math.floor(line));
|
|
528
|
-
} else {
|
|
529
|
-
webScroll.current?.scrollSource(line === firstSource ? 0 : sourcePixel(line));
|
|
530
|
-
}
|
|
531
|
-
},
|
|
532
|
-
source: (offset, atEnd) => {
|
|
533
|
-
if (!split || !sourceRows.length) return;
|
|
534
|
-
const line = Math.min(firstSource + sourceRows.length - 1, firstSource + Math.max(0, offset - sourceTop) / rowHeight);
|
|
535
|
-
visibleSource.current = Math.floor(line);
|
|
536
|
-
if (atEnd && !source.hasNextPage && !preview.hasNextPage) {
|
|
537
|
-
pendingPreview.current = undefined;
|
|
538
|
-
webScroll.current?.scrollPreviewToEnd();
|
|
539
|
-
} else {
|
|
540
|
-
placePreview.current?.(line);
|
|
541
|
-
}
|
|
542
|
-
},
|
|
543
|
-
previewInteraction: () => { pendingPreview.current = undefined; },
|
|
544
|
-
};
|
|
545
|
-
useEffect(() => {
|
|
546
|
-
if (!web) return;
|
|
547
|
-
webScroll.current = bindMarkdownScroll(panelRoot.current, {
|
|
548
|
-
previewStart: () => scrollActions.current?.previewStart() ?? 1,
|
|
549
|
-
preview: (line) => scrollActions.current?.preview(line),
|
|
550
|
-
source: (offset, atEnd) => scrollActions.current?.source(offset, atEnd),
|
|
551
|
-
previewInteraction: () => scrollActions.current?.previewInteraction(),
|
|
552
|
-
});
|
|
553
|
-
return () => {
|
|
554
|
-
webScroll.current?.dispose();
|
|
555
|
-
webScroll.current = undefined;
|
|
556
|
-
};
|
|
557
|
-
}, [web]);
|
|
558
|
-
const followNativePreview = useRef<() => void>(undefined);
|
|
559
|
-
followNativePreview.current = () => {
|
|
560
|
-
if (!previewVisible) return;
|
|
561
|
-
const line = previewOffset.current <= previewHeaderHeight.current + 1 ? targetLine : currentBlock.current?.first;
|
|
562
|
-
if (!line || visibleLine.current === line) return;
|
|
563
|
-
visibleLine.current = line;
|
|
564
|
-
if (split && nativeSplitDriver.current === "preview") jumpToSource(line);
|
|
565
|
-
};
|
|
566
|
-
const onVisible = useRef(({ viewableItems }: { viewableItems: { item: PreviewBlock; isViewable: boolean }[] }) => {
|
|
567
|
-
currentBlock.current = viewableItems.find(({ isViewable }) => isViewable)?.item;
|
|
568
|
-
if (web) schedulePreviewAlignment();
|
|
569
|
-
else followNativePreview.current?.();
|
|
570
|
-
});
|
|
571
|
-
const followNativeSource = useRef<(line: number) => void>(undefined);
|
|
572
|
-
followNativeSource.current = (line) => {
|
|
573
|
-
if (split && nativeSplitDriver.current === "source") jumpToNativePreview(line, 0);
|
|
574
|
-
};
|
|
575
|
-
useEffect(() => {
|
|
576
|
-
if (!web && !preview.isPending) followNativeSource.current?.(visibleSource.current);
|
|
577
|
-
}, [blocks, preview.isPending, web]);
|
|
578
|
-
const onVisibleSource = useRef(({ viewableItems }: { viewableItems: { item: { number: number }; isViewable: boolean }[] }) => {
|
|
579
|
-
const line = viewableItems.find(({ isViewable }) => isViewable)?.item.number;
|
|
580
|
-
if (!line) return;
|
|
581
|
-
visibleSource.current = line;
|
|
582
|
-
if (!web) followNativeSource.current?.(line);
|
|
583
|
-
});
|
|
584
|
-
const viewabilityConfig = useRef({ itemVisiblePercentThreshold: 0 });
|
|
585
|
-
const readingWidth = web ? webReadingWidth : nativeReadingWidth;
|
|
586
|
-
const pane = (visible: boolean): ViewStyle => split
|
|
587
|
-
? { flex: 1, minHeight: 0, minWidth: 0 }
|
|
588
|
-
: { position: "absolute", top: 0, bottom: 0, left: 0, right: 0, opacity: visible ? 1 : 0, zIndex: visible ? 1 : 0,
|
|
589
|
-
...(!visible && web ? hiddenOnWeb : {}) };
|
|
590
|
-
const error = (cause: unknown, retry: () => void) => <ReadError theme={theme} compact={compact} label={t("textError")}
|
|
591
|
-
error={cause} retry={t("retry")} onRetry={retry} />;
|
|
592
|
-
const retryFile = () => setAttempt((value) => value + 1);
|
|
593
|
-
const loadPreview = () => {
|
|
594
|
-
if (preview.hasNextPage && !preview.isFetching && !preview.isError) void preview.fetchNextPage({ cancelRefetch: false });
|
|
595
|
-
};
|
|
596
|
-
const loadSource = () => {
|
|
597
|
-
if (source.hasNextPage && !source.isFetching && !source.isError) void source.fetchNextPage({ cancelRefetch: false });
|
|
598
|
-
};
|
|
599
|
-
return (
|
|
600
|
-
<View ref={panelRoot} testID="merong-text-panel" {...(web ? { tabIndex: 0 } : {})}
|
|
601
|
-
onLayout={({ nativeEvent }) => setPanelWidth(nativeEvent.layout.width)}
|
|
602
|
-
style={{ flex: 1, minHeight: 0, backgroundColor: theme.colors.surface0 }}>
|
|
603
|
-
<Toolbar theme={theme} filePanel={props} lines={info?.lineCount}>
|
|
604
|
-
<Control title={t("preview")} icon="BookOpenText" selected={previewVisible && !split}
|
|
605
|
-
onPress={() => changeMode("preview")} theme={theme} compact={compact} />
|
|
606
|
-
<Control title={t("splitMarkdown")} icon={sideBySide ? "Columns2" : "Rows2"} selected={split} theme={theme} compact={compact}
|
|
607
|
-
onPress={() => { if (!split) { changeMode("split"); jumpToSource(visibleLine.current); } }} />
|
|
608
|
-
<Control title={t("source")} icon="Code" selected={mode === "source"} theme={theme} compact={compact}
|
|
609
|
-
onPress={() => { changeMode("source"); jumpToSource(visibleSource.current, true); }} />
|
|
610
|
-
<Control title={t("find")} icon="Search" selected={findOpen} onPress={findOpen ? closeFind : openFind}
|
|
611
|
-
theme={theme} compact={compact} />
|
|
612
|
-
<ExternalFileAction {...props} />
|
|
613
|
-
</Toolbar>
|
|
614
|
-
{web && (
|
|
615
|
-
<View ref={codeProbe} {...{ dataSet: { pmono: "" } }} pointerEvents="none" accessibilityElementsHidden importantForAccessibility="no-hide-descendants"
|
|
616
|
-
style={[{ position: "absolute", width: 280, left: -300 }, hiddenOnWeb]}>
|
|
617
|
-
<Markdown>{sourceProbeText}</Markdown>
|
|
618
|
-
</View>
|
|
619
|
-
)}
|
|
620
|
-
<View testID={split ? "merong-markdown-split" : undefined}
|
|
621
|
-
style={{ flex: 1, minHeight: 0, minWidth: 0, flexDirection: split && sideBySide ? "row" : "column" }}>
|
|
622
|
-
{hasPreview && (
|
|
623
|
-
<View ref={previewRoot} testID="merong-markdown-preview-pane" style={pane(previewVisible)} pointerEvents={previewVisible ? "auto" : "none"}
|
|
624
|
-
accessibilityElementsHidden={!previewVisible} importantForAccessibility={previewVisible ? "auto" : "no-hide-descendants"}>
|
|
625
|
-
{preview.isPending ? <Loading /> : <FlatList ref={previewList} key={`${version}:${targetLine}`} data={blocks} testID="merong-markdown-preview-scroll"
|
|
626
|
-
keyExtractor={({ key }) => key} keyboardShouldPersistTaps="handled" directionalLockEnabled
|
|
627
|
-
initialNumToRender={6} maxToRenderPerBatch={6} windowSize={5}
|
|
628
|
-
onViewableItemsChanged={onVisible.current} viewabilityConfig={viewabilityConfig.current}
|
|
629
|
-
onScrollToIndexFailed={({ index, averageItemLength }) => {
|
|
630
|
-
if (web) {
|
|
631
|
-
const pending = pendingPreview.current;
|
|
632
|
-
if (!pending) return;
|
|
633
|
-
const line = Math.floor(pending.line);
|
|
634
|
-
if (targetLine !== line) setTargetLine(line);
|
|
635
|
-
else previewList.current?.scrollToOffset({ offset: index * Math.max(averageItemLength, 20), animated: false });
|
|
636
|
-
return;
|
|
637
|
-
}
|
|
638
|
-
const line = nativePreviewJump.current;
|
|
639
|
-
if (line !== undefined && targetLine !== line) setTargetLine(line);
|
|
640
|
-
}}
|
|
641
|
-
onScrollBeginDrag={!web && split ? () => { nativeSplitDriver.current = "preview"; } : undefined}
|
|
642
|
-
onContentSizeChange={web ? undefined : restorePreviewPosition}
|
|
643
|
-
onScroll={web ? undefined : ({ nativeEvent }) => { previewOffset.current = nativeEvent.contentOffset.y; followNativePreview.current?.(); }}
|
|
644
|
-
scrollEventThrottle={32}
|
|
645
|
-
contentContainerStyle={{ paddingHorizontal: compact ? 8 : 16, paddingVertical: 12, gap: 12 }}
|
|
646
|
-
onEndReached={previewVisible ? loadPreview : undefined} onEndReachedThreshold={0.65}
|
|
647
|
-
ListHeaderComponent={targetLine <= (info?.frontMatterEnd ?? 0) && info?.frontMatter.length
|
|
648
|
-
? <View style={[contentFrame, readingWidth]}
|
|
649
|
-
{...(web ? { dataSet: { previewIndex: "-1", sourceFirst: "1", sourceLast: String(info.frontMatterEnd) } } : {})}
|
|
650
|
-
onLayout={({ nativeEvent }) => { previewHeaderHeight.current = nativeEvent.layout.height; }}>
|
|
651
|
-
<Metadata info={info} theme={theme} />
|
|
652
|
-
{previewMatchMarker(1, info.frontMatterEnd)}
|
|
653
|
-
</View> : null}
|
|
654
|
-
ListEmptyComponent={!preview.hasNextPage && !preview.isError && !(info?.frontMatter.length)
|
|
655
|
-
? <Text style={{ color: theme.colors.foregroundMuted }}>{t("empty")}</Text> : null}
|
|
656
|
-
ListFooterComponent={preview.isError ? error(preview.error, retryFile) : preview.isFetchingNextPage
|
|
657
|
-
? <ActivityIndicator /> : preview.hasNextPage
|
|
658
|
-
? <Control title={t("loadMore")} theme={theme} compact={compact} onPress={loadPreview} /> : null}
|
|
659
|
-
renderItem={({ item, index }) => (
|
|
660
|
-
<View testID="merong-markdown-file-frame"
|
|
661
|
-
style={[contentFrame, readingWidth, { flexDirection: "row", gap: 4 }]}
|
|
662
|
-
{...(web ? { dataSet: { previewIndex: String(index), sourceFirst: String(item.first), sourceLast: String(item.last) } } : {})}>
|
|
663
|
-
<View style={{ flex: 1, minWidth: 0 }}>
|
|
664
|
-
<Markdown>{item.text}</Markdown>
|
|
665
|
-
</View>
|
|
666
|
-
<Control title={t("showBlockSource")} icon="Code2" theme={theme} compact={compact} small
|
|
667
|
-
onPress={() => showBlockSource({ first: item.first, last: item.last })} />
|
|
668
|
-
{previewMatchMarker(item.first, item.last)}
|
|
669
|
-
</View>
|
|
670
|
-
)} />}
|
|
671
|
-
</View>
|
|
672
|
-
)}
|
|
673
|
-
{hasSource && (
|
|
674
|
-
<View ref={sourceRoot} testID="merong-markdown-source-pane" {...(web ? { dataSet: { pmono: "" } } : {})}
|
|
675
|
-
style={[pane(sourceVisible), split && { borderColor: theme.colors.border,
|
|
676
|
-
borderLeftWidth: sideBySide ? 1 : 0, borderTopWidth: sideBySide ? 0 : 1 }]}
|
|
677
|
-
pointerEvents={sourceVisible ? "auto" : "none"}
|
|
678
|
-
accessibilityElementsHidden={!sourceVisible} importantForAccessibility={sourceVisible ? "auto" : "no-hide-descendants"}>
|
|
679
|
-
{firstSource > 1 && <Toolbar theme={theme}>
|
|
680
|
-
<Control title={t("earlierLines")} icon="ChevronsUp" theme={theme} compact={compact}
|
|
681
|
-
onPress={() => setSourceLine(Math.max(1, firstSource - 128))} />
|
|
682
|
-
</Toolbar>}
|
|
683
|
-
{source.isPending ? <Loading /> : <SourceScroll wrap={wrapSource} width={sourceWidth}>
|
|
684
|
-
<FlatList ref={sourceList} key={`${version}:${sourceLine}:${wrapSource}`} data={sourceRows} keyExtractor={({ number }) => String(number)}
|
|
685
|
-
testID="merong-markdown-source-scroll"
|
|
686
|
-
style={[{ flex: 1 }, split && fixedSourceScroll]} keyboardShouldPersistTaps="handled" directionalLockEnabled nestedScrollEnabled
|
|
687
|
-
onLayout={web ? undefined : ({ nativeEvent }) => { sourceHeight.current = nativeEvent.layout.height; }}
|
|
688
|
-
onScrollBeginDrag={!web && split ? () => { nativeSplitDriver.current = "source"; } : undefined}
|
|
689
|
-
onScroll={web ? undefined : ({ nativeEvent }) => { sourceOffset.current = nativeEvent.contentOffset.y; }}
|
|
690
|
-
scrollEventThrottle={32}
|
|
691
|
-
onViewableItemsChanged={onVisibleSource.current} viewabilityConfig={viewabilityConfig.current}
|
|
692
|
-
contentContainerStyle={{ paddingVertical: sourceTop }}
|
|
693
|
-
getItemLayout={wrapSource ? undefined : (_, index) => ({ length: rowHeight, offset: sourceTop + index * rowHeight, index })}
|
|
694
|
-
onScrollToIndexFailed={wrapSource ? recoverSourceScroll : undefined}
|
|
695
|
-
initialNumToRender={28} maxToRenderPerBatch={24} windowSize={5}
|
|
696
|
-
onEndReached={sourceVisible ? loadSource : undefined} onEndReachedThreshold={0.75}
|
|
697
|
-
ListFooterComponent={source.isError ? error(source.error, retryFile) : source.isFetchingNextPage ? <ActivityIndicator />
|
|
698
|
-
: source.hasNextPage ? <Control title={t("loadMore")} theme={theme} compact={compact} onPress={loadSource} /> : null}
|
|
699
|
-
renderItem={({ item }) => {
|
|
700
|
-
const flashing = !!flash && item.number >= flash.first && item.number <= flash.last;
|
|
701
|
-
const linked = mode === "source" && linkRange
|
|
702
|
-
&& item.number >= linkRange.first && item.number <= linkRange.last;
|
|
703
|
-
const active = find.active?.line === item.number;
|
|
704
|
-
const matches = hitsByLine.get(item.number);
|
|
705
|
-
const backgroundColor = linked || active ? theme.colors.surface2 : theme.colors.surface0;
|
|
706
|
-
return (
|
|
707
|
-
<View {...(web ? { dataSet: { sourceRow: "true", flash: String(flashing) } } : {})}
|
|
708
|
-
style={{ flexDirection: "row", height: wrapSource ? undefined : rowHeight, minHeight: rowHeight,
|
|
709
|
-
paddingRight: wrapSource ? 2 : 12, backgroundColor }}>
|
|
710
|
-
<View {...(web ? { dataSet: { sourceGutter: "true" } } : {})}
|
|
711
|
-
style={[{ backgroundColor, width: gutterWidth }, web && webGutter,
|
|
712
|
-
web && { borderRightWidth: 1, borderColor: theme.colors.border }]}>
|
|
713
|
-
<Text allowFontScaling={false}
|
|
714
|
-
style={[codeStyle, { color: linked || active ? theme.colors.foreground : theme.colors.foregroundMuted,
|
|
715
|
-
textAlign: "right", paddingRight: web ? 3 : 12 }]}>
|
|
716
|
-
{item.number}
|
|
717
|
-
</Text>
|
|
718
|
-
</View>
|
|
719
|
-
<Text allowFontScaling={false} numberOfLines={!web && !wrapSource ? 1 : undefined} selectable
|
|
720
|
-
style={[codeStyle, { flex: 1, paddingLeft: web ? 6 : 0, color: theme.colors.foreground },
|
|
721
|
-
web && (wrapSource ? wrappedSource : preformatted)]}>
|
|
722
|
-
{matches ? <MatchText text={item.text} matches={matches} active={find.active} theme={theme} />
|
|
723
|
-
: <Syntax source={item.text} theme={theme} hostPalette={web} />}{item.truncated ? "…" : ""}
|
|
724
|
-
</Text>
|
|
725
|
-
{flashing && <Animated.View pointerEvents="none" style={{ position: "absolute", left: 0, right: 0, top: 0, bottom: 0,
|
|
726
|
-
zIndex: 2, backgroundColor: theme.colors.accent, opacity: flashOpacity }} />}
|
|
727
|
-
</View>
|
|
728
|
-
);
|
|
729
|
-
}} />
|
|
730
|
-
</SourceScroll>}
|
|
731
|
-
</View>
|
|
732
|
-
)}
|
|
733
|
-
{findOpen && <ReaderFindBar testID="merong-markdown-find" find={find} theme={theme} compact={compact} close={closeFind} />}
|
|
734
|
-
</View>
|
|
735
|
-
</View>
|
|
736
|
-
);
|
|
737
|
-
}
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
|
2
|
+
import { ActivityIndicator, Animated, Dimensions, Easing, Platform, Text, View, useWindowDimensions,
|
|
3
|
+
type FlatList as NativeFlatList, type TextStyle, type ViewStyle } from "react-native";
|
|
4
|
+
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
|
|
5
|
+
import type { RpcInput, RpcOutput } from "@getpaseo/plugin";
|
|
6
|
+
import { useRpc, useTabState, useTranslation, type PluginFilePanelProps } from "@getpaseo/plugin/client";
|
|
7
|
+
import { FlatList, Loading, Markdown, ScrollView } from "@getpaseo/plugin/client/ui";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { readMarkdownInfo, readMarkdownPage, readMarkdownSource } from "../shared/contracts";
|
|
10
|
+
import { findFormulas, lineOffsets, markdownParser } from "../shared/markdown-math";
|
|
11
|
+
import { inlineReferenceLinks, markdownReferences } from "../shared/markdown-references";
|
|
12
|
+
import { markdownSourceLocation } from "../shared/markdown-source-location";
|
|
13
|
+
import { Control, isTabActive, ReadError, Toolbar, useFileGeneration } from "./controls";
|
|
14
|
+
import { ExternalFileAction } from "./external-file";
|
|
15
|
+
import { bindMarkdownScroll } from "./markdown-scroll";
|
|
16
|
+
import { ReaderFindBar, useMarkdownFind, useReaderFindShortcuts, useReaderFindVisibility, type MarkdownMatch } from "./reader-find";
|
|
17
|
+
import { messages } from "./messages";
|
|
18
|
+
import { Syntax } from "./syntax";
|
|
19
|
+
import { bindMarkdownAnchors, focusReaderFind, observeCodeFont, readerSelection,
|
|
20
|
+
revealMarkdownMatch, webReadingWidth } from "./web";
|
|
21
|
+
|
|
22
|
+
type Page = RpcOutput<typeof readMarkdownPage>;
|
|
23
|
+
type Info = RpcOutput<typeof readMarkdownInfo>;
|
|
24
|
+
type FileTarget = RpcInput<typeof readMarkdownInfo>;
|
|
25
|
+
type PageCursor = Omit<RpcInput<typeof readMarkdownPage>, keyof FileTarget>;
|
|
26
|
+
type LineRange = { first: number; last: number };
|
|
27
|
+
type PreviewBlock = { key: string; first: number; last: number; text: string };
|
|
28
|
+
const markdownTabState = z.object({ mode: z.enum(["source", "preview", "split"]).nullable() });
|
|
29
|
+
type Mode = NonNullable<z.infer<typeof markdownTabState>["mode"]>;
|
|
30
|
+
type SourceRow = RpcOutput<typeof readMarkdownSource>["lines"][number] & { number: number };
|
|
31
|
+
type SourcePosition = { first: number; count: number };
|
|
32
|
+
type SourceJump = { line: number; center: boolean; offset?: number };
|
|
33
|
+
type PreviewJump = { line: number; index?: number; find?: boolean };
|
|
34
|
+
type SplitPane = "preview" | "source";
|
|
35
|
+
const defaultCodeSize = 12;
|
|
36
|
+
const wideSplitWidth = 680;
|
|
37
|
+
const contentFrame = { width: "100%", alignSelf: "center", paddingHorizontal: 8 } as const;
|
|
38
|
+
const nativeReadingWidth = { maxWidth: 820 };
|
|
39
|
+
const cachedBlocks = new WeakMap<Page, { info?: Info; blocks: PreviewBlock[] }>();
|
|
40
|
+
const webGutter = { position: "sticky", left: 0, zIndex: 1 } as unknown as ViewStyle;
|
|
41
|
+
const fixedSourceScroll = { overflowAnchor: "none" } as unknown as ViewStyle;
|
|
42
|
+
const preformatted = { whiteSpace: "pre", tabSize: 4 } as TextStyle;
|
|
43
|
+
const wrappedSource = { whiteSpace: "pre-wrap", overflowWrap: "anywhere", tabSize: 4 } as TextStyle;
|
|
44
|
+
const hiddenOnWeb = { visibility: "hidden" } as unknown as ViewStyle;
|
|
45
|
+
const sourceProbeText = "```\n00000000\n00000000\n```";
|
|
46
|
+
|
|
47
|
+
function SourceScroll({ wrap, width, children }: { wrap: boolean; width: number; children: ReactNode }) {
|
|
48
|
+
if (wrap) return children;
|
|
49
|
+
return <ScrollView horizontal nestedScrollEnabled directionalLockEnabled style={{ flex: 1 }}
|
|
50
|
+
contentContainerStyle={{ minWidth: "100%", width: Math.max(180, width), flexGrow: 1 }}>{children}</ScrollView>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function previewBlocks(page: Page, info?: Info): PreviewBlock[] {
|
|
54
|
+
const cached = cachedBlocks.get(page);
|
|
55
|
+
if (cached && cached.info === info) return cached.blocks;
|
|
56
|
+
const metadataLines = info?.revision === page.revision && page.prefixLines === 0
|
|
57
|
+
? Math.max(0, info.frontMatterEnd - page.firstLine + 1) : 0;
|
|
58
|
+
const source = metadataLines ? page.markdown.slice(lineOffsets(page.markdown)[metadataLines] ?? page.markdown.length) : page.markdown;
|
|
59
|
+
if (!source.trim()) {
|
|
60
|
+
cachedBlocks.set(page, { info, blocks: [] });
|
|
61
|
+
return [];
|
|
62
|
+
}
|
|
63
|
+
const references = info?.revision === page.revision ? info.references : markdownReferences(source);
|
|
64
|
+
const offsets = lineOffsets(source);
|
|
65
|
+
const formulas = findFormulas(source).filter((span) => span.block);
|
|
66
|
+
const starts = markdownParser.parse(source, {}).filter((token) => token.level === 0 && token.map)
|
|
67
|
+
.map((token) => token.map![0]);
|
|
68
|
+
const boundaries = [...new Set([0, ...starts, offsets.length - 1])].filter((line) =>
|
|
69
|
+
!formulas.some((span) => span.start < offsets[line] && offsets[line] < span.end));
|
|
70
|
+
const blocks: PreviewBlock[] = [];
|
|
71
|
+
const sourceBase = page.firstLine + metadataLines - page.prefixLines;
|
|
72
|
+
const lastSource = page.nextLine - Number(/(?:\r\n|\r|\n)$/.test(page.source));
|
|
73
|
+
for (const [index, line] of boundaries.slice(0, -1).entries()) {
|
|
74
|
+
const next = boundaries[index + 1];
|
|
75
|
+
const block = source.slice(offsets[line], offsets[next]).trimEnd();
|
|
76
|
+
if (!block || (block.trimStart().startsWith("[") && !markdownParser.parse(block, {}).length)) continue;
|
|
77
|
+
const first = Math.max(page.firstLine + metadataLines, sourceBase + line);
|
|
78
|
+
const last = Math.max(first, Math.min(lastSource, sourceBase + line + block.split(/\r\n|\r|\n/).length - 1));
|
|
79
|
+
blocks.push({ key: `${page.offset}:${index}`, first, last, text: inlineReferenceLinks(block, references) });
|
|
80
|
+
}
|
|
81
|
+
cachedBlocks.set(page, { info, blocks });
|
|
82
|
+
return blocks;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function Metadata({ info, theme }: { info: Info; theme: PluginFilePanelProps["theme"] }) {
|
|
86
|
+
return (
|
|
87
|
+
<View style={{ backgroundColor: theme.colors.surface1, borderColor: theme.colors.border, borderWidth: 1,
|
|
88
|
+
borderRadius: 8, padding: 12, gap: 6 }}>
|
|
89
|
+
{info.frontMatter.map(({ key, value }) => (
|
|
90
|
+
<View key={key} style={{ flexDirection: "row", gap: 12 }}>
|
|
91
|
+
<Text selectable style={{ flex: 1, color: theme.colors.foregroundMuted, fontWeight: "600" }}>{key}</Text>
|
|
92
|
+
<Text selectable style={{ flex: 2, color: theme.colors.foreground }}>{value}</Text>
|
|
93
|
+
</View>
|
|
94
|
+
))}
|
|
95
|
+
</View>
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function MatchText({ text, matches, active, theme }: {
|
|
100
|
+
text: string; matches: MarkdownMatch[]; active?: MarkdownMatch; theme: PluginFilePanelProps["theme"];
|
|
101
|
+
}) {
|
|
102
|
+
let offset = 0;
|
|
103
|
+
const parts = matches.map((match) => {
|
|
104
|
+
const preceding = text.slice(offset, match.column);
|
|
105
|
+
offset = Math.min(text.length, match.column + match.length);
|
|
106
|
+
if (match.column > text.length) return preceding;
|
|
107
|
+
const selected = match === active;
|
|
108
|
+
return (
|
|
109
|
+
<Text key={match.column}>
|
|
110
|
+
{preceding}<Text {...(selected ? { dataSet: { activeMatch: "true" } } : {})} style={{
|
|
111
|
+
backgroundColor: selected ? theme.colors.accent : theme.colors.surface2,
|
|
112
|
+
color: selected ? theme.colors.accentForeground : theme.colors.foreground,
|
|
113
|
+
...(match.length === 0 ? { borderLeftWidth: 2, borderColor: theme.colors.accent } : {}),
|
|
114
|
+
}}>{text.slice(match.column, offset) || "\u200B"}</Text>
|
|
115
|
+
</Text>
|
|
116
|
+
);
|
|
117
|
+
});
|
|
118
|
+
return <>{parts}{text.slice(offset)}</>;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function MarkdownPanel(props: PluginFilePanelProps) {
|
|
122
|
+
const { file, workspaceId, host, theme, params, revision, layout: { compact, platform } } = props;
|
|
123
|
+
const generation = useFileGeneration(file);
|
|
124
|
+
const { t } = useTranslation(messages);
|
|
125
|
+
const web = platform === "web";
|
|
126
|
+
const tabActive = isTabActive(props.tab);
|
|
127
|
+
const read = useRpc(readMarkdownPage);
|
|
128
|
+
const readInfo = useRpc(readMarkdownInfo);
|
|
129
|
+
const readSource = useRpc(readMarkdownSource);
|
|
130
|
+
const target = useMemo<FileTarget>(() => ({ workspaceId, path: file.path }), [workspaceId, file.path]);
|
|
131
|
+
const [attempt, setAttempt] = useState(0);
|
|
132
|
+
const [panelWidth, setPanelWidth] = useState(0);
|
|
133
|
+
const screen = Dimensions.get("screen");
|
|
134
|
+
const desktopLayout = web || (Platform.OS === "ios" && Platform.isPad)
|
|
135
|
+
|| Math.min(screen.width, screen.height) >= 600;
|
|
136
|
+
const sideBySide = desktopLayout && panelWidth >= wideSplitWidth;
|
|
137
|
+
const defaultMode = sideBySide ? "split" : "preview";
|
|
138
|
+
const [savedView, setTabState] = useTabState(props.tab, markdownTabState, { mode: null });
|
|
139
|
+
const [selectedMode, setMode] = useState(savedView.mode);
|
|
140
|
+
const requestedLine = markdownSourceLocation(params.lineStart)?.first;
|
|
141
|
+
const mode = selectedMode ?? (requestedLine ? "source" : defaultMode);
|
|
142
|
+
const split = mode === "split";
|
|
143
|
+
useEffect(() => {
|
|
144
|
+
if (sideBySide && selectedMode === null && !requestedLine) {
|
|
145
|
+
setMode("split");
|
|
146
|
+
setTabState({ mode: "split" });
|
|
147
|
+
}
|
|
148
|
+
}, [requestedLine, selectedMode, setTabState, sideBySide]);
|
|
149
|
+
const previewVisible = mode !== "source";
|
|
150
|
+
const sourceVisible = mode === "source" || split;
|
|
151
|
+
const [visited, setVisited] = useState({ preview: !requestedLine, source: !!requestedLine });
|
|
152
|
+
useEffect(() => {
|
|
153
|
+
setVisited((current) => {
|
|
154
|
+
const preview = current.preview || previewVisible;
|
|
155
|
+
const source = current.source || sourceVisible;
|
|
156
|
+
return preview === current.preview && source === current.source ? current : { preview, source };
|
|
157
|
+
});
|
|
158
|
+
}, [previewVisible, sourceVisible]);
|
|
159
|
+
const hasPreview = visited.preview || previewVisible;
|
|
160
|
+
const hasSource = visited.source || sourceVisible;
|
|
161
|
+
const [targetLine, setTargetLine] = useState(1);
|
|
162
|
+
const [sourceLine, setSourceLine] = useState(requestedLine ?? 1);
|
|
163
|
+
const [flash, setFlash] = useState<LineRange | undefined>();
|
|
164
|
+
const [sourceJump, setSourceJump] = useState<SourceJump>();
|
|
165
|
+
const [flashOpacity] = useState(() => new Animated.Value(0));
|
|
166
|
+
const { findOpen, showFind, hideFind } = useReaderFindVisibility();
|
|
167
|
+
const defaultFamily = platform === "ios" ? "ui-monospace" : "monospace";
|
|
168
|
+
const [codeFont, setCodeFont] = useState({ size: defaultCodeSize, family: defaultFamily, digitWidth: defaultCodeSize * 0.62 });
|
|
169
|
+
const visibleLine = useRef(1);
|
|
170
|
+
const visibleSource = useRef(requestedLine ?? 1);
|
|
171
|
+
const previewOffset = useRef(0);
|
|
172
|
+
const sourceOffset = useRef(0);
|
|
173
|
+
const sourceHeight = useRef(0);
|
|
174
|
+
const nativeSplitDriver = useRef<SplitPane>(undefined);
|
|
175
|
+
const beforeFind = useRef<{ version: string; mode: Mode; sourceLine: number; sourceOffset: number;
|
|
176
|
+
targetLine: number; previewOffset: number }>(undefined);
|
|
177
|
+
const restorePreview = useRef<{ line: number; offset: number }>(undefined);
|
|
178
|
+
const nativePreviewJump = useRef<number>(undefined);
|
|
179
|
+
const previewHeaderHeight = useRef(0);
|
|
180
|
+
const currentBlock = useRef<PreviewBlock>(undefined);
|
|
181
|
+
const panelRoot = useRef<View>(null);
|
|
182
|
+
const previewRoot = useRef<View>(null);
|
|
183
|
+
const sourceRoot = useRef<View>(null);
|
|
184
|
+
const codeProbe = useRef<View>(null);
|
|
185
|
+
const previewList = useRef<NativeFlatList<PreviewBlock>>(null);
|
|
186
|
+
const sourceList = useRef<NativeFlatList<SourceRow>>(null);
|
|
187
|
+
const sourceWindow = useRef<SourcePosition>({ first: 1, count: 0 });
|
|
188
|
+
const webScroll = useRef<ReturnType<typeof bindMarkdownScroll>>(undefined);
|
|
189
|
+
const pendingPreview = useRef<PreviewJump>(undefined);
|
|
190
|
+
const placePreview = useRef<(line: number) => void>(undefined);
|
|
191
|
+
const previewFrame = useRef<number>(undefined);
|
|
192
|
+
const scrollRetryTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
|
|
193
|
+
const scrollTries = useRef(0);
|
|
194
|
+
const completedJump = useRef<SourceJump>(undefined);
|
|
195
|
+
const version = `${file.modifiedAt}:${generation}:${attempt}`;
|
|
196
|
+
const fileKey = ["merong-docs", "markdown", host.id, workspaceId, file.path, version] as const;
|
|
197
|
+
const find = useMarkdownFind(target, fileKey, tabActive && findOpen);
|
|
198
|
+
const versionRef = useRef(version);
|
|
199
|
+
if (versionRef.current !== version) {
|
|
200
|
+
versionRef.current = version;
|
|
201
|
+
setTargetLine(visibleLine.current);
|
|
202
|
+
setSourceLine(visibleSource.current);
|
|
203
|
+
}
|
|
204
|
+
const changeMode = useCallback((next: Mode) => {
|
|
205
|
+
nativeSplitDriver.current = undefined;
|
|
206
|
+
if (next !== selectedMode) {
|
|
207
|
+
setMode(next);
|
|
208
|
+
setTabState({ mode: next });
|
|
209
|
+
}
|
|
210
|
+
}, [selectedMode, setTabState]);
|
|
211
|
+
const jumpToSource = useCallback((line: number, center = false) => {
|
|
212
|
+
clearTimeout(scrollRetryTimer.current);
|
|
213
|
+
const { first, count } = sourceWindow.current;
|
|
214
|
+
if (line < first || line >= first + count) setSourceLine(Math.max(1, line - (center ? 24 : 0)));
|
|
215
|
+
setSourceJump({ line, center });
|
|
216
|
+
visibleSource.current = line;
|
|
217
|
+
}, []);
|
|
218
|
+
const showPreview = useCallback((line: number) => {
|
|
219
|
+
nativeSplitDriver.current = undefined;
|
|
220
|
+
visibleLine.current = line;
|
|
221
|
+
if (web && previewVisible && placePreview.current) {
|
|
222
|
+
placePreview.current(line);
|
|
223
|
+
} else {
|
|
224
|
+
previewOffset.current = 0;
|
|
225
|
+
setTargetLine(line);
|
|
226
|
+
}
|
|
227
|
+
beforeFind.current = undefined;
|
|
228
|
+
if (findOpen) hideFind();
|
|
229
|
+
if (split) jumpToSource(line);
|
|
230
|
+
}, [findOpen, hideFind, jumpToSource, previewVisible, split, web]);
|
|
231
|
+
const infoQuery = useQuery({
|
|
232
|
+
queryKey: [...fileKey, "info"], queryFn: () => readInfo(target), staleTime: Infinity, gcTime: 30_000, retry: false,
|
|
233
|
+
});
|
|
234
|
+
const info = infoQuery.data;
|
|
235
|
+
const linkRange = markdownSourceLocation(params.lineStart, params.lineEnd, info?.lineCount);
|
|
236
|
+
const linkStart = linkRange?.first;
|
|
237
|
+
const handledLocation = useRef<{ line: number; revision: number }>(undefined);
|
|
238
|
+
useEffect(() => {
|
|
239
|
+
if (!linkStart) {
|
|
240
|
+
handledLocation.current = undefined;
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (handledLocation.current?.line === linkStart && handledLocation.current.revision === revision) return;
|
|
244
|
+
handledLocation.current = { line: linkStart, revision };
|
|
245
|
+
beforeFind.current = undefined;
|
|
246
|
+
if (findOpen) hideFind();
|
|
247
|
+
if (pendingPreview.current?.find) pendingPreview.current = undefined;
|
|
248
|
+
nativePreviewJump.current = undefined;
|
|
249
|
+
changeMode("source");
|
|
250
|
+
jumpToSource(linkStart, true);
|
|
251
|
+
}, [linkStart, revision, changeMode, findOpen, hideFind, jumpToSource]);
|
|
252
|
+
useEffect(() => () => {
|
|
253
|
+
clearTimeout(scrollRetryTimer.current);
|
|
254
|
+
if (previewFrame.current !== undefined) cancelAnimationFrame(previewFrame.current);
|
|
255
|
+
}, []);
|
|
256
|
+
useEffect(() => {
|
|
257
|
+
if (!web) return;
|
|
258
|
+
return observeCodeFont(codeProbe.current, (size, family, digitWidth) => {
|
|
259
|
+
const resolvedFamily = family || defaultFamily;
|
|
260
|
+
setCodeFont((prior) => prior.size === size && prior.family === resolvedFamily && prior.digitWidth === digitWidth
|
|
261
|
+
? prior : { size, family: resolvedFamily, digitWidth });
|
|
262
|
+
});
|
|
263
|
+
}, [web, defaultFamily]);
|
|
264
|
+
|
|
265
|
+
const preview = useInfiniteQuery({
|
|
266
|
+
queryKey: [...fileKey, "preview", targetLine],
|
|
267
|
+
queryFn: ({ pageParam }) => read({ ...target, ...pageParam }),
|
|
268
|
+
initialPageParam: { offset: 0, atLine: targetLine > 1 ? targetLine : undefined } as PageCursor,
|
|
269
|
+
getNextPageParam: ({ nextOffset, nextLine, revision, fence, table }): PageCursor | undefined => nextOffset === null ? undefined
|
|
270
|
+
: { offset: nextOffset, firstLine: nextLine, revision, fence, table },
|
|
271
|
+
enabled: hasPreview, staleTime: Infinity, gcTime: 30_000, retry: false,
|
|
272
|
+
});
|
|
273
|
+
const source = useInfiniteQuery({
|
|
274
|
+
queryKey: [...fileKey, "source", sourceLine],
|
|
275
|
+
queryFn: ({ pageParam }) => readSource({ ...target, line: pageParam }),
|
|
276
|
+
initialPageParam: sourceLine,
|
|
277
|
+
getNextPageParam: (page) => page.nextLine ?? undefined,
|
|
278
|
+
enabled: hasSource, staleTime: Infinity, gcTime: 30_000, retry: false,
|
|
279
|
+
});
|
|
280
|
+
const anchors = useMemo(() => new Map(info?.headings.filter(({ anchor }) => anchor).map(({ anchor, line }) =>
|
|
281
|
+
[`#${encodeURIComponent(anchor)}`, () => showPreview(line)])), [info, showPreview]);
|
|
282
|
+
const anchorsRef = useRef(anchors);
|
|
283
|
+
anchorsRef.current = anchors;
|
|
284
|
+
useEffect(() => {
|
|
285
|
+
if (!web || !hasPreview) return;
|
|
286
|
+
return bindMarkdownAnchors(previewRoot.current, (href) => {
|
|
287
|
+
let key = href;
|
|
288
|
+
try { key = `#${encodeURIComponent(decodeURIComponent(href.slice(1)))}`; } catch { return false; }
|
|
289
|
+
const action = anchorsRef.current.get(key);
|
|
290
|
+
action?.();
|
|
291
|
+
return !!action;
|
|
292
|
+
});
|
|
293
|
+
}, [web, hasPreview]);
|
|
294
|
+
|
|
295
|
+
const blocks = useMemo(() => preview.data?.pages.flatMap((page, index) => {
|
|
296
|
+
const pageBlocks = previewBlocks(page, info);
|
|
297
|
+
return index > 0 ? pageBlocks : pageBlocks.filter((block) => block.last >= targetLine);
|
|
298
|
+
}) ?? [], [info, preview.data, targetLine]);
|
|
299
|
+
const sourceRows = useMemo(() => source.data?.pages.flatMap((page) => page.lines.map((line, index) =>
|
|
300
|
+
({ ...line, number: page.firstLine + index }))) ?? [], [source.data]);
|
|
301
|
+
const firstSource = sourceRows[0]?.number ?? sourceLine;
|
|
302
|
+
sourceWindow.current = { first: firstSource, count: sourceRows.length };
|
|
303
|
+
const flashLoaded = !!flash && flash.first >= firstSource && flash.first < firstSource + sourceRows.length;
|
|
304
|
+
useEffect(() => {
|
|
305
|
+
if (!sourceVisible || !flashLoaded) return;
|
|
306
|
+
const flashFrame = requestAnimationFrame(() => {
|
|
307
|
+
flashOpacity.setValue(0.24);
|
|
308
|
+
Animated.timing(flashOpacity, {
|
|
309
|
+
toValue: 0, duration: 920, delay: 130, easing: Easing.out(Easing.quad), useNativeDriver: !web,
|
|
310
|
+
}).start(({ finished }) => {
|
|
311
|
+
if (finished) setFlash((current) => current === flash ? undefined : current);
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
return () => {
|
|
315
|
+
cancelAnimationFrame(flashFrame);
|
|
316
|
+
flashOpacity.stopAnimation();
|
|
317
|
+
};
|
|
318
|
+
}, [flash, flashLoaded, flashOpacity, sourceVisible, web]);
|
|
319
|
+
const dimensions = useWindowDimensions();
|
|
320
|
+
const fontScale = web ? 1 : dimensions.fontScale;
|
|
321
|
+
const sourceFontSize = codeFont.size * fontScale;
|
|
322
|
+
const rowHeight = sourceFontSize * 1.45;
|
|
323
|
+
const codeStyle = { fontFamily: codeFont.family, fontSize: sourceFontSize, lineHeight: rowHeight, includeFontPadding: false } as const;
|
|
324
|
+
const wrapSource = mode === "source" && (!web || /\.(?:md|markdown)$/i.test(file.name) && file.size <= 1024 * 1024);
|
|
325
|
+
const sourceTop = web ? 16 : 0;
|
|
326
|
+
const sourcePixel = (line: number) => sourceTop + (line - firstSource) * rowHeight;
|
|
327
|
+
const showBlockSource = (range: LineRange) => {
|
|
328
|
+
changeMode(split || sideBySide ? "split" : "source");
|
|
329
|
+
const viewport = split ? web ? webScroll.current?.sourceViewport() : { top: sourceOffset.current, height: sourceHeight.current } : undefined;
|
|
330
|
+
const first = sourcePixel(range.first);
|
|
331
|
+
const end = sourcePixel(range.last + 1);
|
|
332
|
+
const shown = viewport && range.first >= firstSource && range.first < firstSource + sourceRows.length
|
|
333
|
+
&& first >= viewport.top - 1
|
|
334
|
+
&& (end - first > viewport.height ? first + rowHeight : end) <= viewport.top + viewport.height + 1;
|
|
335
|
+
if (!shown) jumpToSource(range.first, true);
|
|
336
|
+
setFlash({ ...range });
|
|
337
|
+
};
|
|
338
|
+
const gutterWidth = web ? Math.max(21, Math.ceil(String(info?.lineCount ?? sourceRows.at(-1)?.number ?? 1).length * codeFont.digitWidth + 9))
|
|
339
|
+
: Math.max(56, String(info?.lineCount ?? sourceRows.at(-1)?.number ?? 1).length * sourceFontSize * 0.62 + 15);
|
|
340
|
+
const sourceWidth = useMemo(() => wrapSource ? 0 : Math.min(26_000, sourceRows.reduce((width, { text }) => {
|
|
341
|
+
const length = text.length + (text.match(/[\u2e80-\uffef\t]/g)?.length ?? 0) * 2;
|
|
342
|
+
return Math.max(width, gutterWidth + 19 + length * sourceFontSize * 0.67);
|
|
343
|
+
}, 0)), [gutterWidth, sourceFontSize, sourceRows, wrapSource]);
|
|
344
|
+
const hitsByLine = useMemo(() => {
|
|
345
|
+
const groups = new Map<number, MarkdownMatch[]>();
|
|
346
|
+
for (const hit of find.hits) {
|
|
347
|
+
const group = groups.get(hit.line);
|
|
348
|
+
if (group) group.push(hit);
|
|
349
|
+
else groups.set(hit.line, [hit]);
|
|
350
|
+
}
|
|
351
|
+
return groups;
|
|
352
|
+
}, [find.hits]);
|
|
353
|
+
const openFind = () => {
|
|
354
|
+
if (findOpen) return focusReaderFind(panelRoot.current, "merong-markdown-find");
|
|
355
|
+
if (!web) beforeFind.current = {
|
|
356
|
+
version, mode, sourceLine, sourceOffset: sourceOffset.current, targetLine, previewOffset: previewOffset.current,
|
|
357
|
+
};
|
|
358
|
+
const selected = web ? readerSelection(panelRoot.current) : "";
|
|
359
|
+
if (selected && !selected.includes("\n")) find.changeQuery(selected.slice(0, 256));
|
|
360
|
+
showFind();
|
|
361
|
+
};
|
|
362
|
+
const closeFind = () => {
|
|
363
|
+
hideFind();
|
|
364
|
+
const saved = beforeFind.current;
|
|
365
|
+
beforeFind.current = undefined;
|
|
366
|
+
nativePreviewJump.current = undefined;
|
|
367
|
+
if (pendingPreview.current?.find) pendingPreview.current = undefined;
|
|
368
|
+
if (saved?.version !== version) return;
|
|
369
|
+
clearTimeout(scrollRetryTimer.current);
|
|
370
|
+
changeMode(saved.mode);
|
|
371
|
+
if (saved.mode !== "preview") {
|
|
372
|
+
setSourceLine(saved.sourceLine);
|
|
373
|
+
setSourceJump({ line: saved.sourceLine, center: false, offset: saved.sourceOffset });
|
|
374
|
+
}
|
|
375
|
+
if (saved.mode === "source") return;
|
|
376
|
+
if (targetLine !== saved.targetLine) {
|
|
377
|
+
restorePreview.current = { line: saved.targetLine, offset: saved.previewOffset };
|
|
378
|
+
setTargetLine(saved.targetLine);
|
|
379
|
+
} else if (previewOffset.current !== saved.previewOffset) {
|
|
380
|
+
previewList.current?.scrollToOffset({ offset: saved.previewOffset, animated: false });
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
useReaderFindShortcuts(panelRoot, "merong-markdown-find", web && tabActive,
|
|
384
|
+
{ open: openFind, close: closeFind, move: find.move, isOpen: () => findOpen });
|
|
385
|
+
useEffect(() => {
|
|
386
|
+
if (!sourceVisible || !sourceJump || sourceJump === completedJump.current ||
|
|
387
|
+
sourceJump.line < firstSource || sourceJump.line >= firstSource + sourceRows.length) return;
|
|
388
|
+
const frame = requestAnimationFrame(() => {
|
|
389
|
+
const list = sourceList.current;
|
|
390
|
+
if (!list) return;
|
|
391
|
+
completedJump.current = sourceJump;
|
|
392
|
+
scrollTries.current = 0;
|
|
393
|
+
const offset = sourceTop + (sourceJump.line - firstSource) * rowHeight;
|
|
394
|
+
const scroller = split ? webScroll.current : undefined;
|
|
395
|
+
const viewport = scroller?.sourceViewport();
|
|
396
|
+
if (viewport && scroller?.scrollSource(sourceJump.center
|
|
397
|
+
? offset - (viewport.height - rowHeight) * 0.35 : sourceJump.offset ?? offset)) return;
|
|
398
|
+
if (sourceJump.center) {
|
|
399
|
+
list.scrollToIndex({ index: sourceJump.line - firstSource, viewPosition: 0.35, animated: false });
|
|
400
|
+
} else {
|
|
401
|
+
list.scrollToOffset({ offset: sourceJump.offset ?? Math.max(0, sourceJump.line - firstSource) * rowHeight, animated: false });
|
|
402
|
+
}
|
|
403
|
+
});
|
|
404
|
+
return () => cancelAnimationFrame(frame);
|
|
405
|
+
}, [firstSource, rowHeight, sourceJump, sourceRows.length, sourceTop, sourceVisible, split]);
|
|
406
|
+
const recoverSourceScroll = ({ index, averageItemLength }: { index: number; averageItemLength: number }) => {
|
|
407
|
+
if (scrollTries.current++ >= 3) return;
|
|
408
|
+
const list = sourceList.current;
|
|
409
|
+
list?.scrollToOffset({ offset: index * (averageItemLength || rowHeight), animated: false });
|
|
410
|
+
scrollRetryTimer.current = setTimeout(() => {
|
|
411
|
+
if (list && list === sourceList.current) list.scrollToIndex({ index, viewPosition: 0.35, animated: false });
|
|
412
|
+
}, 70);
|
|
413
|
+
};
|
|
414
|
+
useEffect(() => {
|
|
415
|
+
if (!web || !find.active || sourceJump?.line !== find.active.line || !sourceVisible ||
|
|
416
|
+
find.active.line < firstSource || find.active.line >= firstSource + sourceRows.length) return;
|
|
417
|
+
const timeout = setTimeout(() => revealMarkdownMatch(sourceRoot.current), 100);
|
|
418
|
+
return () => clearTimeout(timeout);
|
|
419
|
+
}, [find.active, firstSource, sourceJump, sourceRows.length, sourceVisible, web]);
|
|
420
|
+
const alignPreview = useRef<() => void>(undefined);
|
|
421
|
+
alignPreview.current = () => {
|
|
422
|
+
const pending = pendingPreview.current;
|
|
423
|
+
const scroller = webScroll.current;
|
|
424
|
+
if (!pending || !scroller || preview.isPending) return;
|
|
425
|
+
if (scroller.scrollPreview(pending.line, pending.find)) {
|
|
426
|
+
pendingPreview.current = undefined;
|
|
427
|
+
visibleLine.current = Math.floor(pending.line);
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
const last = blocks.at(-1);
|
|
431
|
+
if (pending.line < targetLine || last && pending.line > last.last + 1 && preview.hasNextPage) {
|
|
432
|
+
if (preview.isFetching) return;
|
|
433
|
+
if (pending.line >= targetLine && last && pending.line < last.last + 128) {
|
|
434
|
+
void preview.fetchNextPage({ cancelRefetch: false });
|
|
435
|
+
} else {
|
|
436
|
+
setTargetLine(Math.max(1, Math.floor(pending.line)));
|
|
437
|
+
}
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
if (!last || pending.line > last.last + 1) {
|
|
441
|
+
scroller.scrollPreviewToEnd();
|
|
442
|
+
pendingPreview.current = undefined;
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
const next = blocks.findIndex((block) => block.first > pending.line);
|
|
446
|
+
const index = Math.max(0, (next < 0 ? blocks.length : next) - 1);
|
|
447
|
+
if (index === pending.index || !previewList.current) return;
|
|
448
|
+
pending.index = index;
|
|
449
|
+
previewList.current.scrollToIndex({ index, animated: false });
|
|
450
|
+
};
|
|
451
|
+
placePreview.current = (line) => {
|
|
452
|
+
pendingPreview.current = { line, index: pendingPreview.current?.index };
|
|
453
|
+
alignPreview.current?.();
|
|
454
|
+
};
|
|
455
|
+
const schedulePreviewAlignment = useCallback(() => {
|
|
456
|
+
if (!pendingPreview.current || previewFrame.current !== undefined) return;
|
|
457
|
+
previewFrame.current = requestAnimationFrame(() => {
|
|
458
|
+
previewFrame.current = undefined;
|
|
459
|
+
alignPreview.current?.();
|
|
460
|
+
});
|
|
461
|
+
}, []);
|
|
462
|
+
useEffect(() => {
|
|
463
|
+
schedulePreviewAlignment();
|
|
464
|
+
}, [blocks, preview.isFetching, schedulePreviewAlignment, targetLine]);
|
|
465
|
+
|
|
466
|
+
const jumpToNativePreview = (line: number, viewPosition: number) => {
|
|
467
|
+
if (line <= (info?.frontMatterEnd ?? 0)) {
|
|
468
|
+
if (targetLine === 1) previewList.current?.scrollToOffset({ offset: 0, animated: false });
|
|
469
|
+
else setTargetLine(1);
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
const next = blocks.findIndex(({ first }) => first > line);
|
|
473
|
+
const index = next < 0 ? blocks.length - 1 : Math.max(0, next - 1);
|
|
474
|
+
const last = blocks.at(-1);
|
|
475
|
+
if (!last || line < targetLine || (line > last.last && preview.hasNextPage) || !previewList.current) {
|
|
476
|
+
if (!viewPosition && preview.isPending) return;
|
|
477
|
+
if (targetLine !== line) setTargetLine(line);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
if (!viewPosition && blocks[index] === currentBlock.current && previewOffset.current > previewHeaderHeight.current + 1) return;
|
|
481
|
+
nativePreviewJump.current = line;
|
|
482
|
+
previewList.current.scrollToIndex({ index, viewPosition, animated: false });
|
|
483
|
+
nativePreviewJump.current = undefined;
|
|
484
|
+
};
|
|
485
|
+
const navigateToMatch = useRef<(match: MarkdownMatch) => void>(undefined);
|
|
486
|
+
navigateToMatch.current = (match) => {
|
|
487
|
+
nativeSplitDriver.current = undefined;
|
|
488
|
+
if (sourceVisible) jumpToSource(match.line, true);
|
|
489
|
+
if (!previewVisible) return;
|
|
490
|
+
if (web) {
|
|
491
|
+
pendingPreview.current = { line: match.line, find: true };
|
|
492
|
+
schedulePreviewAlignment();
|
|
493
|
+
} else {
|
|
494
|
+
jumpToNativePreview(match.line, 0.25);
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
useEffect(() => {
|
|
498
|
+
if (find.active) navigateToMatch.current?.(find.active);
|
|
499
|
+
else {
|
|
500
|
+
nativePreviewJump.current = undefined;
|
|
501
|
+
if (pendingPreview.current?.find) pendingPreview.current = undefined;
|
|
502
|
+
}
|
|
503
|
+
}, [find.active, previewVisible, sourceVisible]);
|
|
504
|
+
const restorePreviewPosition = () => {
|
|
505
|
+
const restore = restorePreview.current;
|
|
506
|
+
if (!restore || restore.line !== targetLine || !previewList.current) return;
|
|
507
|
+
restorePreview.current = undefined;
|
|
508
|
+
previewList.current.scrollToOffset({ offset: restore.offset, animated: false });
|
|
509
|
+
};
|
|
510
|
+
const previewMatchMarker = (first: number, last: number) => {
|
|
511
|
+
const line = find.active?.line;
|
|
512
|
+
return previewVisible && line !== undefined && line >= first && line <= last
|
|
513
|
+
? <View testID="merong-markdown-preview-match" pointerEvents="none" style={{ position: "absolute",
|
|
514
|
+
left: 1, top: 0, bottom: 0, width: 2, borderRadius: 1, backgroundColor: theme.colors.accent }} />
|
|
515
|
+
: null;
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
const scrollActions = useRef<Parameters<typeof bindMarkdownScroll>[1]>(undefined);
|
|
519
|
+
scrollActions.current = {
|
|
520
|
+
previewStart: () => targetLine,
|
|
521
|
+
preview: (line) => {
|
|
522
|
+
if (pendingPreview.current) return schedulePreviewAlignment();
|
|
523
|
+
if (!previewVisible || line === undefined) return;
|
|
524
|
+
visibleLine.current = Math.floor(line);
|
|
525
|
+
if (!split) return;
|
|
526
|
+
if (line < firstSource || line >= firstSource + sourceRows.length) {
|
|
527
|
+
if (Math.floor(line) !== sourceJump?.line) jumpToSource(Math.floor(line));
|
|
528
|
+
} else {
|
|
529
|
+
webScroll.current?.scrollSource(line === firstSource ? 0 : sourcePixel(line));
|
|
530
|
+
}
|
|
531
|
+
},
|
|
532
|
+
source: (offset, atEnd) => {
|
|
533
|
+
if (!split || !sourceRows.length) return;
|
|
534
|
+
const line = Math.min(firstSource + sourceRows.length - 1, firstSource + Math.max(0, offset - sourceTop) / rowHeight);
|
|
535
|
+
visibleSource.current = Math.floor(line);
|
|
536
|
+
if (atEnd && !source.hasNextPage && !preview.hasNextPage) {
|
|
537
|
+
pendingPreview.current = undefined;
|
|
538
|
+
webScroll.current?.scrollPreviewToEnd();
|
|
539
|
+
} else {
|
|
540
|
+
placePreview.current?.(line);
|
|
541
|
+
}
|
|
542
|
+
},
|
|
543
|
+
previewInteraction: () => { pendingPreview.current = undefined; },
|
|
544
|
+
};
|
|
545
|
+
useEffect(() => {
|
|
546
|
+
if (!web) return;
|
|
547
|
+
webScroll.current = bindMarkdownScroll(panelRoot.current, {
|
|
548
|
+
previewStart: () => scrollActions.current?.previewStart() ?? 1,
|
|
549
|
+
preview: (line) => scrollActions.current?.preview(line),
|
|
550
|
+
source: (offset, atEnd) => scrollActions.current?.source(offset, atEnd),
|
|
551
|
+
previewInteraction: () => scrollActions.current?.previewInteraction(),
|
|
552
|
+
});
|
|
553
|
+
return () => {
|
|
554
|
+
webScroll.current?.dispose();
|
|
555
|
+
webScroll.current = undefined;
|
|
556
|
+
};
|
|
557
|
+
}, [web]);
|
|
558
|
+
const followNativePreview = useRef<() => void>(undefined);
|
|
559
|
+
followNativePreview.current = () => {
|
|
560
|
+
if (!previewVisible) return;
|
|
561
|
+
const line = previewOffset.current <= previewHeaderHeight.current + 1 ? targetLine : currentBlock.current?.first;
|
|
562
|
+
if (!line || visibleLine.current === line) return;
|
|
563
|
+
visibleLine.current = line;
|
|
564
|
+
if (split && nativeSplitDriver.current === "preview") jumpToSource(line);
|
|
565
|
+
};
|
|
566
|
+
const onVisible = useRef(({ viewableItems }: { viewableItems: { item: PreviewBlock; isViewable: boolean }[] }) => {
|
|
567
|
+
currentBlock.current = viewableItems.find(({ isViewable }) => isViewable)?.item;
|
|
568
|
+
if (web) schedulePreviewAlignment();
|
|
569
|
+
else followNativePreview.current?.();
|
|
570
|
+
});
|
|
571
|
+
const followNativeSource = useRef<(line: number) => void>(undefined);
|
|
572
|
+
followNativeSource.current = (line) => {
|
|
573
|
+
if (split && nativeSplitDriver.current === "source") jumpToNativePreview(line, 0);
|
|
574
|
+
};
|
|
575
|
+
useEffect(() => {
|
|
576
|
+
if (!web && !preview.isPending) followNativeSource.current?.(visibleSource.current);
|
|
577
|
+
}, [blocks, preview.isPending, web]);
|
|
578
|
+
const onVisibleSource = useRef(({ viewableItems }: { viewableItems: { item: { number: number }; isViewable: boolean }[] }) => {
|
|
579
|
+
const line = viewableItems.find(({ isViewable }) => isViewable)?.item.number;
|
|
580
|
+
if (!line) return;
|
|
581
|
+
visibleSource.current = line;
|
|
582
|
+
if (!web) followNativeSource.current?.(line);
|
|
583
|
+
});
|
|
584
|
+
const viewabilityConfig = useRef({ itemVisiblePercentThreshold: 0 });
|
|
585
|
+
const readingWidth = web ? webReadingWidth : nativeReadingWidth;
|
|
586
|
+
const pane = (visible: boolean): ViewStyle => split
|
|
587
|
+
? { flex: 1, minHeight: 0, minWidth: 0 }
|
|
588
|
+
: { position: "absolute", top: 0, bottom: 0, left: 0, right: 0, opacity: visible ? 1 : 0, zIndex: visible ? 1 : 0,
|
|
589
|
+
...(!visible && web ? hiddenOnWeb : {}) };
|
|
590
|
+
const error = (cause: unknown, retry: () => void) => <ReadError theme={theme} compact={compact} label={t("textError")}
|
|
591
|
+
error={cause} retry={t("retry")} onRetry={retry} />;
|
|
592
|
+
const retryFile = () => setAttempt((value) => value + 1);
|
|
593
|
+
const loadPreview = () => {
|
|
594
|
+
if (preview.hasNextPage && !preview.isFetching && !preview.isError) void preview.fetchNextPage({ cancelRefetch: false });
|
|
595
|
+
};
|
|
596
|
+
const loadSource = () => {
|
|
597
|
+
if (source.hasNextPage && !source.isFetching && !source.isError) void source.fetchNextPage({ cancelRefetch: false });
|
|
598
|
+
};
|
|
599
|
+
return (
|
|
600
|
+
<View ref={panelRoot} testID="merong-text-panel" {...(web ? { tabIndex: 0 } : {})}
|
|
601
|
+
onLayout={({ nativeEvent }) => setPanelWidth(nativeEvent.layout.width)}
|
|
602
|
+
style={{ flex: 1, minHeight: 0, backgroundColor: theme.colors.surface0 }}>
|
|
603
|
+
<Toolbar theme={theme} filePanel={props} lines={info?.lineCount}>
|
|
604
|
+
<Control title={t("preview")} icon="BookOpenText" selected={previewVisible && !split}
|
|
605
|
+
onPress={() => changeMode("preview")} theme={theme} compact={compact} />
|
|
606
|
+
<Control title={t("splitMarkdown")} icon={sideBySide ? "Columns2" : "Rows2"} selected={split} theme={theme} compact={compact}
|
|
607
|
+
onPress={() => { if (!split) { changeMode("split"); jumpToSource(visibleLine.current); } }} />
|
|
608
|
+
<Control title={t("source")} icon="Code" selected={mode === "source"} theme={theme} compact={compact}
|
|
609
|
+
onPress={() => { changeMode("source"); jumpToSource(visibleSource.current, true); }} />
|
|
610
|
+
<Control title={t("find")} icon="Search" selected={findOpen} onPress={findOpen ? closeFind : openFind}
|
|
611
|
+
theme={theme} compact={compact} />
|
|
612
|
+
<ExternalFileAction {...props} />
|
|
613
|
+
</Toolbar>
|
|
614
|
+
{web && (
|
|
615
|
+
<View ref={codeProbe} {...{ dataSet: { pmono: "" } }} pointerEvents="none" accessibilityElementsHidden importantForAccessibility="no-hide-descendants"
|
|
616
|
+
style={[{ position: "absolute", width: 280, left: -300 }, hiddenOnWeb]}>
|
|
617
|
+
<Markdown>{sourceProbeText}</Markdown>
|
|
618
|
+
</View>
|
|
619
|
+
)}
|
|
620
|
+
<View testID={split ? "merong-markdown-split" : undefined}
|
|
621
|
+
style={{ flex: 1, minHeight: 0, minWidth: 0, flexDirection: split && sideBySide ? "row" : "column" }}>
|
|
622
|
+
{hasPreview && (
|
|
623
|
+
<View ref={previewRoot} testID="merong-markdown-preview-pane" style={pane(previewVisible)} pointerEvents={previewVisible ? "auto" : "none"}
|
|
624
|
+
accessibilityElementsHidden={!previewVisible} importantForAccessibility={previewVisible ? "auto" : "no-hide-descendants"}>
|
|
625
|
+
{preview.isPending ? <Loading /> : <FlatList ref={previewList} key={`${version}:${targetLine}`} data={blocks} testID="merong-markdown-preview-scroll"
|
|
626
|
+
keyExtractor={({ key }) => key} keyboardShouldPersistTaps="handled" directionalLockEnabled
|
|
627
|
+
initialNumToRender={6} maxToRenderPerBatch={6} windowSize={5}
|
|
628
|
+
onViewableItemsChanged={onVisible.current} viewabilityConfig={viewabilityConfig.current}
|
|
629
|
+
onScrollToIndexFailed={({ index, averageItemLength }) => {
|
|
630
|
+
if (web) {
|
|
631
|
+
const pending = pendingPreview.current;
|
|
632
|
+
if (!pending) return;
|
|
633
|
+
const line = Math.floor(pending.line);
|
|
634
|
+
if (targetLine !== line) setTargetLine(line);
|
|
635
|
+
else previewList.current?.scrollToOffset({ offset: index * Math.max(averageItemLength, 20), animated: false });
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
const line = nativePreviewJump.current;
|
|
639
|
+
if (line !== undefined && targetLine !== line) setTargetLine(line);
|
|
640
|
+
}}
|
|
641
|
+
onScrollBeginDrag={!web && split ? () => { nativeSplitDriver.current = "preview"; } : undefined}
|
|
642
|
+
onContentSizeChange={web ? undefined : restorePreviewPosition}
|
|
643
|
+
onScroll={web ? undefined : ({ nativeEvent }) => { previewOffset.current = nativeEvent.contentOffset.y; followNativePreview.current?.(); }}
|
|
644
|
+
scrollEventThrottle={32}
|
|
645
|
+
contentContainerStyle={{ paddingHorizontal: compact ? 8 : 16, paddingVertical: 12, gap: 12 }}
|
|
646
|
+
onEndReached={previewVisible ? loadPreview : undefined} onEndReachedThreshold={0.65}
|
|
647
|
+
ListHeaderComponent={targetLine <= (info?.frontMatterEnd ?? 0) && info?.frontMatter.length
|
|
648
|
+
? <View style={[contentFrame, readingWidth]}
|
|
649
|
+
{...(web ? { dataSet: { previewIndex: "-1", sourceFirst: "1", sourceLast: String(info.frontMatterEnd) } } : {})}
|
|
650
|
+
onLayout={({ nativeEvent }) => { previewHeaderHeight.current = nativeEvent.layout.height; }}>
|
|
651
|
+
<Metadata info={info} theme={theme} />
|
|
652
|
+
{previewMatchMarker(1, info.frontMatterEnd)}
|
|
653
|
+
</View> : null}
|
|
654
|
+
ListEmptyComponent={!preview.hasNextPage && !preview.isError && !(info?.frontMatter.length)
|
|
655
|
+
? <Text style={{ color: theme.colors.foregroundMuted }}>{t("empty")}</Text> : null}
|
|
656
|
+
ListFooterComponent={preview.isError ? error(preview.error, retryFile) : preview.isFetchingNextPage
|
|
657
|
+
? <ActivityIndicator /> : preview.hasNextPage
|
|
658
|
+
? <Control title={t("loadMore")} theme={theme} compact={compact} onPress={loadPreview} /> : null}
|
|
659
|
+
renderItem={({ item, index }) => (
|
|
660
|
+
<View testID="merong-markdown-file-frame"
|
|
661
|
+
style={[contentFrame, readingWidth, { flexDirection: "row", gap: 4 }]}
|
|
662
|
+
{...(web ? { dataSet: { previewIndex: String(index), sourceFirst: String(item.first), sourceLast: String(item.last) } } : {})}>
|
|
663
|
+
<View style={{ flex: 1, minWidth: 0 }}>
|
|
664
|
+
<Markdown>{item.text}</Markdown>
|
|
665
|
+
</View>
|
|
666
|
+
<Control title={t("showBlockSource")} icon="Code2" theme={theme} compact={compact} small
|
|
667
|
+
onPress={() => showBlockSource({ first: item.first, last: item.last })} />
|
|
668
|
+
{previewMatchMarker(item.first, item.last)}
|
|
669
|
+
</View>
|
|
670
|
+
)} />}
|
|
671
|
+
</View>
|
|
672
|
+
)}
|
|
673
|
+
{hasSource && (
|
|
674
|
+
<View ref={sourceRoot} testID="merong-markdown-source-pane" {...(web ? { dataSet: { pmono: "" } } : {})}
|
|
675
|
+
style={[pane(sourceVisible), split && { borderColor: theme.colors.border,
|
|
676
|
+
borderLeftWidth: sideBySide ? 1 : 0, borderTopWidth: sideBySide ? 0 : 1 }]}
|
|
677
|
+
pointerEvents={sourceVisible ? "auto" : "none"}
|
|
678
|
+
accessibilityElementsHidden={!sourceVisible} importantForAccessibility={sourceVisible ? "auto" : "no-hide-descendants"}>
|
|
679
|
+
{firstSource > 1 && <Toolbar theme={theme}>
|
|
680
|
+
<Control title={t("earlierLines")} icon="ChevronsUp" theme={theme} compact={compact}
|
|
681
|
+
onPress={() => setSourceLine(Math.max(1, firstSource - 128))} />
|
|
682
|
+
</Toolbar>}
|
|
683
|
+
{source.isPending ? <Loading /> : <SourceScroll wrap={wrapSource} width={sourceWidth}>
|
|
684
|
+
<FlatList ref={sourceList} key={`${version}:${sourceLine}:${wrapSource}`} data={sourceRows} keyExtractor={({ number }) => String(number)}
|
|
685
|
+
testID="merong-markdown-source-scroll"
|
|
686
|
+
style={[{ flex: 1 }, split && fixedSourceScroll]} keyboardShouldPersistTaps="handled" directionalLockEnabled nestedScrollEnabled
|
|
687
|
+
onLayout={web ? undefined : ({ nativeEvent }) => { sourceHeight.current = nativeEvent.layout.height; }}
|
|
688
|
+
onScrollBeginDrag={!web && split ? () => { nativeSplitDriver.current = "source"; } : undefined}
|
|
689
|
+
onScroll={web ? undefined : ({ nativeEvent }) => { sourceOffset.current = nativeEvent.contentOffset.y; }}
|
|
690
|
+
scrollEventThrottle={32}
|
|
691
|
+
onViewableItemsChanged={onVisibleSource.current} viewabilityConfig={viewabilityConfig.current}
|
|
692
|
+
contentContainerStyle={{ paddingVertical: sourceTop }}
|
|
693
|
+
getItemLayout={wrapSource ? undefined : (_, index) => ({ length: rowHeight, offset: sourceTop + index * rowHeight, index })}
|
|
694
|
+
onScrollToIndexFailed={wrapSource ? recoverSourceScroll : undefined}
|
|
695
|
+
initialNumToRender={28} maxToRenderPerBatch={24} windowSize={5}
|
|
696
|
+
onEndReached={sourceVisible ? loadSource : undefined} onEndReachedThreshold={0.75}
|
|
697
|
+
ListFooterComponent={source.isError ? error(source.error, retryFile) : source.isFetchingNextPage ? <ActivityIndicator />
|
|
698
|
+
: source.hasNextPage ? <Control title={t("loadMore")} theme={theme} compact={compact} onPress={loadSource} /> : null}
|
|
699
|
+
renderItem={({ item }) => {
|
|
700
|
+
const flashing = !!flash && item.number >= flash.first && item.number <= flash.last;
|
|
701
|
+
const linked = mode === "source" && linkRange
|
|
702
|
+
&& item.number >= linkRange.first && item.number <= linkRange.last;
|
|
703
|
+
const active = find.active?.line === item.number;
|
|
704
|
+
const matches = hitsByLine.get(item.number);
|
|
705
|
+
const backgroundColor = linked || active ? theme.colors.surface2 : theme.colors.surface0;
|
|
706
|
+
return (
|
|
707
|
+
<View {...(web ? { dataSet: { sourceRow: "true", flash: String(flashing) } } : {})}
|
|
708
|
+
style={{ flexDirection: "row", height: wrapSource ? undefined : rowHeight, minHeight: rowHeight,
|
|
709
|
+
paddingRight: wrapSource ? 2 : 12, backgroundColor }}>
|
|
710
|
+
<View {...(web ? { dataSet: { sourceGutter: "true" } } : {})}
|
|
711
|
+
style={[{ backgroundColor, width: gutterWidth }, web && webGutter,
|
|
712
|
+
web && { borderRightWidth: 1, borderColor: theme.colors.border }]}>
|
|
713
|
+
<Text allowFontScaling={false}
|
|
714
|
+
style={[codeStyle, { color: linked || active ? theme.colors.foreground : theme.colors.foregroundMuted,
|
|
715
|
+
textAlign: "right", paddingRight: web ? 3 : 12 }]}>
|
|
716
|
+
{item.number}
|
|
717
|
+
</Text>
|
|
718
|
+
</View>
|
|
719
|
+
<Text allowFontScaling={false} numberOfLines={!web && !wrapSource ? 1 : undefined} selectable
|
|
720
|
+
style={[codeStyle, { flex: 1, paddingLeft: web ? 6 : 0, color: theme.colors.foreground },
|
|
721
|
+
web && (wrapSource ? wrappedSource : preformatted)]}>
|
|
722
|
+
{matches ? <MatchText text={item.text} matches={matches} active={find.active} theme={theme} />
|
|
723
|
+
: <Syntax source={item.text} theme={theme} hostPalette={web} />}{item.truncated ? "…" : ""}
|
|
724
|
+
</Text>
|
|
725
|
+
{flashing && <Animated.View pointerEvents="none" style={{ position: "absolute", left: 0, right: 0, top: 0, bottom: 0,
|
|
726
|
+
zIndex: 2, backgroundColor: theme.colors.accent, opacity: flashOpacity }} />}
|
|
727
|
+
</View>
|
|
728
|
+
);
|
|
729
|
+
}} />
|
|
730
|
+
</SourceScroll>}
|
|
731
|
+
</View>
|
|
732
|
+
)}
|
|
733
|
+
{findOpen && <ReaderFindBar testID="merong-markdown-find" find={find} theme={theme} compact={compact} close={closeFind} />}
|
|
734
|
+
</View>
|
|
735
|
+
</View>
|
|
736
|
+
);
|
|
737
|
+
}
|