paseo-omni-reader 0.0.0-stage → 0.1.1

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.
Files changed (58) hide show
  1. package/OVERVIEW.md +13 -0
  2. package/OVERVIEW.zh-CN.md +13 -0
  3. package/README.md +42 -2
  4. package/README.zh-CN.md +43 -0
  5. package/assets/chat-zh-CN.png +0 -0
  6. package/assets/cover-en.png +0 -0
  7. package/assets/excel-zh-CN.png +0 -0
  8. package/assets/icon.png +0 -0
  9. package/assets/markdown-zh-CN.png +0 -0
  10. package/assets/pdf-en.png +0 -0
  11. package/assets/powerpoint-en.png +0 -0
  12. package/assets/settings-zh-CN.png +0 -0
  13. package/client/android-file-share.ts +25 -0
  14. package/client/assistant-turn.ts +35 -0
  15. package/client/controls.tsx +92 -0
  16. package/client/document-panel.tsx +109 -0
  17. package/client/external-file.tsx +76 -0
  18. package/client/file-reader.tsx +134 -0
  19. package/client/markdown-panel.tsx +94 -0
  20. package/client/markdown.tsx +460 -0
  21. package/client/messages.ts +144 -0
  22. package/client/native-contacts.ts +134 -0
  23. package/client/native-markdown.tsx +210 -0
  24. package/client/page-render-queue.ts +12 -0
  25. package/client/pdf-geometry.ts +87 -0
  26. package/client/pdf-panel.tsx +323 -0
  27. package/client/reader-open-gate.ts +17 -0
  28. package/client/reader-scroll.tsx +15 -0
  29. package/client/settings.tsx +43 -0
  30. package/client/viewport-geometry.ts +47 -0
  31. package/client/web.ts +291 -0
  32. package/client/worksheet-panel.tsx +278 -0
  33. package/client/zoom-controls.tsx +140 -0
  34. package/index.client.tsx +35 -0
  35. package/index.server.ts +49 -0
  36. package/npm-shrinkwrap.json +690 -0
  37. package/package.json +33 -4
  38. package/paseo-plugin.json +24 -0
  39. package/server/assets.d.ts +4 -0
  40. package/server/engine.ts +84 -0
  41. package/server/external-file.ts +42 -0
  42. package/server/generated/document-worker.ts +1 -0
  43. package/server/generated/math-worker.ts +1 -0
  44. package/server/markdown-links.ts +41 -0
  45. package/server/markdown-page.ts +120 -0
  46. package/server/math-engine.ts +140 -0
  47. package/server/office-preview.ts +197 -0
  48. package/server/office-xml.ts +71 -0
  49. package/server/pdf-engine.ts +127 -0
  50. package/server/structured-document.ts +70 -0
  51. package/server/worker-entry.ts +38 -0
  52. package/server/worker-protocol.ts +27 -0
  53. package/server/worksheet.ts +250 -0
  54. package/server/workspace-file.ts +63 -0
  55. package/shared/contracts.ts +144 -0
  56. package/shared/markdown-math.ts +179 -0
  57. package/shared/reader-settings.ts +14 -0
  58. package/shared/reading-blocks.ts +91 -0
package/OVERVIEW.md ADDED
@@ -0,0 +1,13 @@
1
+ # Paseo Omni Reader
2
+
3
+ Omni Reader provides read-only workspace previews for Markdown, PDF, Word, Excel and PowerPoint. Open files in the main panel or on the side using Paseo’s **Open location** settings. The plugin also renders LaTeX in streaming assistant replies. Use **Restore original reply** to switch back to Paseo’s Markdown.
4
+
5
+ Use Paseo 0.17.5 or newer on the daemon and client. The plugin supports browser, desktop, iOS and Android clients. If Paseo asks which Markdown viewer to use, choose Omni Reader and remember the choice. A Git installation requires Node.js 22 or newer and npm on the daemon host. The plugin builds its rendering worker from locked dependencies during installation.
6
+
7
+ Inline fractions get room for the numerator and denominator. Standalone equations are centered. Both follow Paseo’s chat content font size, with separate size presets from 50% to 200% in the plugin settings. Hover for LaTeX or click to copy in a browser. Touch and hold any formula in the native app to show or copy its LaTeX. Failed formulas keep their source and offer a retry.
8
+
9
+ Markdown supports the same LaTeX as chat, a source view, and loading large files as you read. PDF and formatted Office pages scroll vertically. At 100%, an entire page fits the viewport by width or height. Use the toolbar or focus the preview and press `+`, `-`, or `0`. PDFs can be up to 128 MiB. For Office files up to 24 MiB, LibreOffice on the Paseo host renders formatted Word pages, Excel print layouts and PowerPoint slides. Excel also opens in a scrollable read-only worksheet grid that works without LibreOffice.
10
+
11
+ On iOS and Android, Omni Reader shows file content in full screen so swipes stay inside the reader. Pinch to zoom and drag with one finger in PDF pages, formatted Office pages, and Excel worksheets. In Paseo 0.17.6, the full-screen × returns to the file header. Use Paseo’s × to close the file or the full-screen icon to reopen it.
12
+
13
+ For workspaces on the local Paseo Desktop daemon, **Open externally** opens the original in the system’s default app. Browsers and remote desktop workspaces download a copy. On iOS and Android, the action uses the system share sheet. If sharing is unavailable on Android, download the file from Paseo’s file menu. The daemon reads files in the workspace and returns rendered content to the connected Paseo client. The plugin uses no external rendering service.
@@ -0,0 +1,13 @@
1
+ # Paseo Omni Reader
2
+
3
+ Omni Reader 为工作区中的 Markdown、PDF、Word、Excel 和 PowerPoint 提供只读预览。文件可按 Paseo 的「打开位置」设置在主面板或侧边打开。插件也会在流式助手回复中渲染 LaTeX。点击**还原原始回复**可切回 Paseo 的 Markdown。
4
+
5
+ 守护进程和客户端均需 Paseo 0.17.5 或更新版本,支持浏览器、桌面客户端、iOS 和 Android。如果 Paseo 询问 Markdown 的打开方式,选择 Omni Reader 并记住。通过 Git 安装时,守护进程主机需有 Node.js 22 或更新版本及 npm。插件在安装时根据锁定的依赖构建渲染进程。
6
+
7
+ 行内分数按分子和分母所需的高度排版,独立公式居中。聊天中的两种公式均跟随 Paseo 的内容字号,插件设置可分别选择 50% 至 200% 的字号档位。浏览器中悬停可看 LaTeX 原文,点击可复制。原生 App 中长按任意公式即可显示或复制 LaTeX。渲染失败时会保留源码并提供重试。
8
+
9
+ Markdown 可显示与聊天相同的 LaTeX、切换源码,并随阅读加载大文件。PDF 和带排版的 Office 预览可连续上下滚动。100% 时整页按宽度或高度适配。使用工具栏缩放,也可点击预览后按 `+`、`-` 或 `0`。PDF 预览上限为 128 MiB。在 Paseo 主机安装 LibreOffice 后,最大 24 MiB 的 Office 文件可按 Word 页面、Excel 打印版式和 PowerPoint 幻灯片预览。Excel 还提供无需 LibreOffice 的可滚动只读工作表网格。
10
+
11
+ 在 iOS 和 Android 上,Omni Reader 以全屏显示文件内容,滑动手势留在阅读器内。PDF、带排版的 Office 页面和 Excel 工作表可双指缩放、单指平移。Paseo 0.17.6 中,点全屏右上角的 × 返回文件标题栏,再点 Paseo 的 × 关闭文件,或点全屏图标重新打开。
12
+
13
+ 使用 Paseo 桌面客户端打开本机工作区时,「在外部打开」会使用系统默认应用打开原件。浏览器和桌面端的远程工作区下载副本。iOS 和 Android 通过系统分享交给其他 App。Android 系统分享不可用时,可从 Paseo 文件菜单下载。守护进程读取工作区文件并通过 Paseo 连接返回预览结果,插件无需外部渲染服务。
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ <img src="assets/icon.png" alt="" width="96">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # Paseo Omni Reader
4
+
5
+ [简体中文](README.zh-CN.md)
6
+
7
+ Omni Reader adds LaTeX to streaming assistant replies and read-only previews for Markdown, PDF, Word, Excel and PowerPoint.
8
+
9
+ ![Paseo Omni Reader cover with an inline fraction, a formula table, a centered equation, and links to notes and a PDF](assets/cover-en.png)
10
+
11
+ ## What you can read
12
+
13
+ - **Assistant replies.** Complete formulas render during streaming. Inline fractions have room to show their numerator and denominator, and standalone equations are centered. Tables size their columns to their content and center when they fit. Wide tables and long code scroll horizontally. Hover to see LaTeX or click to copy in a browser. Touch and hold any formula in the native app to see or copy its source. Use **Restore original reply** below an enhanced reply to return to Paseo’s Markdown. **Resume rendering** appears in the same spot. Paseo provides the turn footer in both views. Inline and display formulas follow Paseo’s content font size. Choose a separate size preset from 50% to 200% for each in the plugin settings.
14
+ - **Workspace files.** Open Markdown, `.pdf`, `.docx`, `.xlsx`, and `.pptx` from chat links or the file tree. Paseo’s **Open location** settings let you choose the main panel or side pane separately for chat links and file tree selections. Phones use Paseo’s file preview sheet. Markdown uses the same formula settings as chat, supports preview/source switching, and loads large documents as you read.
15
+ - **Continuous pages.** PDF and formatted Office pages stack vertically. At 100%, each entire page fits the preview with either its width or height filling the available space. Drag the zoom slider or enter a percentage from 25% to 400%. Hover over toolbar icons for labels. Scroll with the mouse wheel and drag to pan. Click the preview and press `+`, `-`, or `0` to zoom in, zoom out, or fit the page. On native clients, pinch to zoom and pan with one finger.
16
+ - **Excel worksheets.** Read sheets in a scrollable grid with row and column headings, workbook tabs, merged cells, and basic cell styling. Columns expand to fit their contents and long text wraps onto taller rows. Pinch to zoom and drag with one finger on a phone. Use **Print layout** to view the formatted print output and charts when LibreOffice is available on the Paseo host.
17
+ - **External editing.** In Paseo Desktop, **Open externally** opens the original file in the system’s default app when the workspace is on the local daemon. Browsers and remote desktop workspaces download a copy. On iOS and Android, the action hands a copy to the system share sheet. On Android builds where sharing is unavailable, use **Download** from Paseo’s file menu.
18
+
19
+ | PDF reader | PowerPoint preview |
20
+ | --- | --- |
21
+ | ![Landscape PDF survey plate followed by a portrait page in continuous view](assets/pdf-en.png) | ![PowerPoint slide with a line chart, slide navigation and zoom controls](assets/powerpoint-en.png) |
22
+
23
+ See the [Excel worksheet with wrapped notes](assets/excel-zh-CN.png), [Markdown preview with formulas and code](assets/markdown-zh-CN.png), [Simplified Chinese chat example](assets/chat-zh-CN.png), and [bilingual formula size settings](assets/settings-zh-CN.png).
24
+
25
+ ## Install from GitHub
26
+
27
+ Use Paseo 0.17.5 or newer on the client and daemon. Paseo 0.17.5 is the first release that preserves native reply actions, including branching and turn statistics, alongside enhanced replies. The daemon host needs Node.js 22 or newer and npm for Git installation.
28
+
29
+ ```sh
30
+ paseo plugin install github:Fu021/paseo-omni-reader
31
+ ```
32
+
33
+ Paseo opens the preview directly when Omni Reader is the only available viewer. If Paseo asks about Markdown, choose Omni Reader and remember the choice. Plugin controls are in Simplified Chinese when Paseo uses Simplified Chinese, and in English for other locales.
34
+
35
+ On a phone, Omni Reader shows file content in full screen to keep swipes inside the preview. In Paseo 0.17.6, the full-screen × returns you to the file header, and Paseo’s × closes the file. Use the full-screen icon beside the file name to reopen the preview.
36
+
37
+ ## Data and limits
38
+
39
+ The Paseo daemon reads files inside the active workspace and sends rendered content to the connected client. Install LibreOffice Writer, Calc, and Impress on that host to see formatting, images, charts, and pagination in Office print previews. The browser and native apps display the same read-only previews. The Excel worksheet grid works without LibreOffice. Without LibreOffice, Word and PowerPoint offer basic text previews. PDF previews accept files up to 128 MiB and Office previews accept files up to 24 MiB. Failed formulas keep their source and offer a retry.
40
+
41
+ For development, run `npm ci --include=dev --ignore-scripts`, `npm run typecheck`, `npm test`, and `npm run check:package`. With LibreOffice Writer, Calc and Impress installed, run `npm run test:office` to test formatted Office previews. GitHub Actions runs these checks on Linux with Node.js 22 and 24, with LibreOffice on Node.js 24. See the marketplace overviews in [English](OVERVIEW.md) and [简体中文](OVERVIEW.zh-CN.md).
42
+
43
+ `npm run pack:release` builds the npm archive with the rendering workers and locked dependencies. `npm run check:package` also installs the archive locally in a temporary directory to check that it works with lifecycle scripts disabled.
@@ -0,0 +1,43 @@
1
+ <img src="assets/icon.png" alt="" width="96">
2
+
3
+ # Paseo Omni Reader
4
+
5
+ [English](README.md)
6
+
7
+ Omni Reader 是 Paseo 阅览增强插件。它为流式聊天加入 LaTeX 排版,也为工作区里的 Markdown、PDF、Word、Excel 和 PowerPoint 提供只读预览。
8
+
9
+ ![Paseo 中文回复中的行内分数、公式表格、居中公式和文件链接](assets/chat-zh-CN.png)
10
+
11
+ ## 阅览体验
12
+
13
+ - **聊天公式。** 流式回复中的公式闭合后即可渲染。行内分数按分子和分母所需的高度排版,独立公式居中。表格按内容调整列宽,放得下时居中,宽表格和长代码各自横向滚动。浏览器悬停看 LaTeX 原文,点击复制。原生 App 长按任意公式即可查看或复制。点击回复下方的**还原原始回复**可切回 Paseo 的 Markdown,同一位置会显示**恢复增强渲染**。两种视图都使用 Paseo 的回合页脚。行内和独立公式都跟随 Paseo 的内容字号,在插件设置中可分别选择 50% 至 200% 的字号档位。
14
+ - **工作区文件。** 从聊天链接或文件树打开 Markdown、`.pdf`、`.docx`、`.xlsx` 和 `.pptx`。在 Paseo 的「打开位置」里,可分别设置聊天链接和文件树打开在主面板还是侧边。手机使用 Paseo 的文件预览窗口。Markdown 使用与聊天相同的公式设置,可切换预览和源码,长文档按需加载。
15
+ - **连续页面。** PDF 和带排版的 Office 预览按页上下排列。100% 时每页完整显示,宽度或高度贴合可用区域。拖动滑杆或输入 25% 至 400% 的百分比可调整缩放,鼠标悬停工具栏图标可查看提示。滚轮上下滚动,按住左键拖动平移。点击预览后按 `+`、`-`、`0` 放大、缩小或恢复适合页面。原生 App 支持双指缩放和单指平移。
16
+ - **Excel 工作表。** 在网格中双向滚动,按底部标签切换工作表。网格显示行号和列标,保留合并单元格和基础样式。列宽随内容扩展,长文本换行并增加行高。手机上可双指缩放、单指平移。在 Paseo 主机安装 LibreOffice 后,可切换到「打印版式」查看图表和打印效果。
17
+ - **外部编辑。** 在 Paseo 桌面客户端中,本机守护进程上的文件可通过「在外部打开」交给系统默认应用打开原件。浏览器和桌面端的远程工作区下载副本。iOS 和 Android 通过系统分享交给其他 App。Android 系统分享不可用时,可从 Paseo 文件菜单下载副本。
18
+
19
+ | PDF 阅读器 | PowerPoint 预览 |
20
+ | --- | --- |
21
+ | ![连续滚动中的横版 PDF 航拍图与下一张竖版页面](assets/pdf-en.png) | ![PowerPoint 幻灯片中的折线图、页码和缩放控件](assets/powerpoint-en.png) |
22
+
23
+ 查看[自动换行的 Excel 备注](assets/excel-zh-CN.png)、[带公式和代码的 Markdown 预览](assets/markdown-zh-CN.png)和[双语公式字号设置](assets/settings-zh-CN.png)。
24
+
25
+ ## 从 GitHub 安装
26
+
27
+ Paseo 客户端和 daemon 均需 0.17.5 或更新版本。从 0.17.5 起,增强回复可以保留原生的分支和回合统计等操作。通过 Git 安装时,daemon 主机需有 Node.js 22 或更新版本及 npm。
28
+
29
+ ```sh
30
+ paseo plugin install github:Fu021/paseo-omni-reader
31
+ ```
32
+
33
+ 只有 Omni Reader 可用时,Paseo 会直接打开文件。如果 Paseo 询问 Markdown 的打开方式,选择 Omni Reader 并记住。Paseo 使用简体中文时显示中文插件控件,其余语言使用英文。
34
+
35
+ 手机上以全屏显示文件内容,让滑动手势留在预览内。Paseo 0.17.6 中,点全屏右上角的 × 返回文件标题栏,再点 Paseo 的 × 关闭文件。也可点文件名旁的全屏图标重新打开预览。
36
+
37
+ ## 数据和限制
38
+
39
+ 插件读取当前工作区内的文件,守护进程通过 Paseo 连接发送预览结果。在运行 Paseo 守护进程的主机安装 LibreOffice Writer、Calc 和 Impress 后,Office 打印预览会保留排版、图片、图表和分页。浏览器和原生 App 使用同一套只读预览。Excel 工作表网格无需 LibreOffice,未安装 LibreOffice 时,Word 和 PowerPoint 可查看基本文本。PDF 预览上限为 128 MiB,Office 预览上限为 24 MiB。渲染失败的公式会保留源码并提供重试。
40
+
41
+ 开发时可运行 `npm ci --include=dev --ignore-scripts`、`npm run typecheck`、`npm test` 和 `npm run check:package`。安装 LibreOffice Writer、Calc 和 Impress 后,可以运行 `npm run test:office` 验证 Office 排版预览。GitHub Actions 在 Linux 上使用 Node.js 22 和 24 执行检查,其中 Node.js 24 包含 LibreOffice 测试。插件市场介绍备有[简体中文](OVERVIEW.zh-CN.md)与 [English](OVERVIEW.md) 版本。
42
+
43
+ `npm run pack:release` 生成包含渲染进程和锁定依赖的 npm 压缩包。`npm run check:package` 还会在临时目录安装该包,验证关闭生命周期脚本后仍可安装。
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,25 @@
1
+ import type { PluginFile } from "@getpaseo/plugin/client";
2
+
3
+ interface ExpoSharingModule {
4
+ shareAsync(url: string, options: { dialogTitle: string; mimeType?: string }): Promise<void>;
5
+ }
6
+
7
+ export async function shareAndroidFile(
8
+ file: Pick<PluginFile, "url" | "mimeType">,
9
+ dialogTitle: string,
10
+ ): Promise<boolean> {
11
+ const { expo } = globalThis as typeof globalThis & {
12
+ expo?: { modules?: { ExpoSharing?: ExpoSharingModule } };
13
+ };
14
+ const sharing = expo?.modules?.ExpoSharing;
15
+ if (typeof sharing?.shareAsync !== "function") return false;
16
+
17
+ const url = await file.url();
18
+ if (!url.startsWith("file:///")) return false;
19
+ const mimeType = file.mimeType.trim().toLowerCase();
20
+ await sharing.shareAsync(url, {
21
+ dialogTitle,
22
+ mimeType: mimeType && mimeType !== "application/octet-stream" ? mimeType : undefined,
23
+ });
24
+ return true;
25
+ }
@@ -0,0 +1,35 @@
1
+ import type { PluginTimelineTransformerContribution } from "@getpaseo/plugin/client";
2
+ import { markdownKind } from "../shared/contracts";
3
+ import { findFormulas } from "../shared/markdown-math";
4
+
5
+ export type AssistantReply = { text: string; messageId?: string };
6
+
7
+ export function assistantReplyKey({ messageId, text }: AssistantReply): string {
8
+ return messageId ? `id:${messageId}` : `text:${text}`;
9
+ }
10
+
11
+ type AssistantTransformInput = Parameters<PluginTimelineTransformerContribution<"assistant_message">["transform"]>[0];
12
+
13
+ export function assistantReplacement({ item, phase }: AssistantTransformInput, plain: boolean) {
14
+ return {
15
+ items: [{
16
+ type: "plugin" as const, kind: markdownKind, version: 1,
17
+ data: {
18
+ text: item.text,
19
+ phase,
20
+ ...(item.messageId ? { messageId: item.messageId } : {}),
21
+ ...(plain ? { plain: true as const } : {}),
22
+ },
23
+ }],
24
+ };
25
+ }
26
+
27
+ function canReplaceAssistant(text: string): boolean {
28
+ return text.length <= 160_000 && Boolean(text.trim()) &&
29
+ !/^ {0,3}(?:`{3,}|~{3,})\s*(?:ui|app)\b/m.test(text);
30
+ }
31
+
32
+ export function shouldReplaceAssistant(text: string): boolean {
33
+ return canReplaceAssistant(text) &&
34
+ (/(?:^|\n) {0,3}(?:`{3,}|~{3,})|\|[ \t]*:?-{2,}/.test(text) || findFormulas(text).length > 0);
35
+ }
@@ -0,0 +1,92 @@
1
+ import { useTranslation, type PluginHostProps } from "@getpaseo/plugin/client";
2
+ import { Icon } from "@getpaseo/plugin/client/ui";
3
+ import { Platform, Pressable, Text, View } from "react-native";
4
+ import { useEffect, useRef, useState, type ReactNode } from "react";
5
+ import type { PluginFilePanelProps } from "@getpaseo/plugin/client";
6
+ import { messages } from "./messages";
7
+ import { setWebTitle } from "./web";
8
+
9
+ export type Theme = PluginHostProps["theme"];
10
+
11
+ export function useWebTitle<T = View>(value?: string) {
12
+ const ref = useRef<T>(null);
13
+ useEffect(() => {
14
+ if (Platform.OS === "web" && value) return setWebTitle(ref.current, value);
15
+ }, [value]);
16
+ return ref;
17
+ }
18
+
19
+ export function Control({ title, icon, theme, compact, disabled = false, selected, onPress }: {
20
+ title: string;
21
+ icon?: string;
22
+ theme: Theme;
23
+ compact: boolean;
24
+ disabled?: boolean;
25
+ selected?: boolean;
26
+ onPress: () => void;
27
+ }) {
28
+ const hint = useWebTitle(icon ? title : undefined);
29
+ return (
30
+ <Pressable
31
+ ref={hint}
32
+ onPress={onPress}
33
+ disabled={disabled}
34
+ accessibilityRole="button"
35
+ accessibilityLabel={title}
36
+ accessibilityState={{ disabled, selected }}
37
+ style={({ pressed, hovered }: { pressed: boolean; hovered?: boolean }) => ({
38
+ height: compact ? 40 : 32,
39
+ minWidth: compact ? 40 : 32,
40
+ paddingHorizontal: icon ? 0 : 8,
41
+ borderRadius: 6,
42
+ alignItems: "center",
43
+ justifyContent: "center",
44
+ backgroundColor: selected || pressed || hovered ? theme.colors.surface2 : "transparent",
45
+ opacity: disabled ? 0.45 : 1,
46
+ })}
47
+ >
48
+ {icon ? <Icon name={icon} size={18} color={theme.colors.foreground} /> : (
49
+ <Text style={{ color: theme.colors.foreground, fontSize: 13, fontWeight: selected ? "600" : "500" }}>
50
+ {title}
51
+ </Text>
52
+ )}
53
+ </Pressable>
54
+ );
55
+ }
56
+
57
+ export function Toolbar({ theme, children }: { theme: Theme; children: ReactNode }) {
58
+ return (
59
+ <View style={{
60
+ alignItems: "center", flexDirection: "row", flexWrap: "wrap", gap: 4,
61
+ paddingHorizontal: 8, paddingVertical: 4, borderBottomWidth: 1,
62
+ borderBottomColor: theme.colors.border, backgroundColor: theme.colors.surface0,
63
+ }}>{children}</View>
64
+ );
65
+ }
66
+
67
+ export function ReadError({ theme, label, error, retry, onRetry, compact }: {
68
+ theme: Theme; label: string; error: unknown; retry: string; onRetry: () => void; compact: boolean;
69
+ }) {
70
+ const { t } = useTranslation(messages);
71
+ const message = error instanceof Error ? error.message : "";
72
+ const detail = message.includes("128 MiB reader limit") ? t("pdfTooLarge")
73
+ : message.includes("Document exceeds the preview limit") ? t("documentTooLarge")
74
+ : message.includes("supports UTF-8") ? t("textEncoding")
75
+ : message.includes("File changed") || message.includes("File ended") ? t("fileChanged")
76
+ : message.includes("outside the workspace") ? t("outsideWorkspace")
77
+ : message.includes("File is no longer available") || message.includes("ENOENT") ? t("fileUnavailable")
78
+ : undefined;
79
+ return (
80
+ <View accessibilityRole="alert" style={{ alignItems: "flex-start", gap: 6, padding: 16 }}>
81
+ <Text style={{ color: theme.colors.foreground, fontWeight: "600" }}>{label}</Text>
82
+ {detail && <Text selectable style={{ color: theme.colors.foregroundMuted }}>{detail}</Text>}
83
+ <Control title={retry} onPress={onRetry} theme={theme} compact={compact} />
84
+ </View>
85
+ );
86
+ }
87
+
88
+ export function useFileGeneration(file: PluginFilePanelProps["file"]) {
89
+ const [generation, setGeneration] = useState(0);
90
+ useEffect(() => file.watch(() => setGeneration((value) => value + 1)), [file]);
91
+ return generation;
92
+ }
@@ -0,0 +1,109 @@
1
+ import { useMemo, useState } from "react";
2
+ import { Text, View } from "react-native";
3
+ import { useQuery } from "@tanstack/react-query";
4
+ import { useRpc, useTranslation, type PluginFilePanelProps } from "@getpaseo/plugin/client";
5
+ import { Loading } from "@getpaseo/plugin/client/ui";
6
+ import { readStructuredDocument, type DocumentBlock } from "../shared/contracts";
7
+ import { Control, ReadError, Toolbar, useFileGeneration, type Theme } from "./controls";
8
+ import { ExternalFileAction } from "./external-file";
9
+ import { messages } from "./messages";
10
+ import { ReaderFlatList as FlatList, ReaderScrollView as ScrollView } from "./reader-scroll";
11
+
12
+ function DataTable({ block, theme }: {
13
+ block: Extract<DocumentBlock, { kind: "table" }>; theme: Theme;
14
+ }) {
15
+ const widths = useMemo(() => {
16
+ const columns: number[] = [];
17
+ for (const row of block.rows) {
18
+ for (const [column, value] of row.entries()) {
19
+ const length = value.length + (value.match(/[\u2e80-\uffef]/g)?.length ?? 0);
20
+ columns[column] = Math.max(columns[column] ?? 0, Math.min(240, Math.max(84, 24 + 8 * length)));
21
+ }
22
+ }
23
+ return columns;
24
+ }, [block]);
25
+ const renderRow = (row: string[], index: number) => (
26
+ <View key={index} role="row" style={{
27
+ flexDirection: "row", borderBottomWidth: 1, borderColor: theme.colors.border,
28
+ backgroundColor: index % 2 ? theme.colors.surface1 : theme.colors.surface0,
29
+ }}>
30
+ {widths.map((width, column) => (
31
+ <Text key={column} selectable style={{
32
+ color: theme.colors.foreground, width, paddingHorizontal: 10, paddingVertical: 8,
33
+ borderRightWidth: 1, borderColor: theme.colors.border,
34
+ }}>{row[column] ?? ""}</Text>
35
+ ))}
36
+ </View>
37
+ );
38
+ return (
39
+ <ScrollView
40
+ horizontal nestedScrollEnabled testID="omni-document-table"
41
+ style={{ flexGrow: 0, maxWidth: "100%" }}
42
+ contentContainerStyle={{ borderLeftWidth: 1, borderTopWidth: 1, borderColor: theme.colors.border }}
43
+ >
44
+ <View>{block.rows.map(renderRow)}</View>
45
+ </ScrollView>
46
+ );
47
+ }
48
+
49
+ export function StructuredPanel(props: PluginFilePanelProps) {
50
+ const { file, host, workspaceId, theme, layout: { compact } } = props;
51
+ const { t } = useTranslation(messages);
52
+ const rpc = useRpc(readStructuredDocument);
53
+ const generation = useFileGeneration(file);
54
+ const [selected, setSelected] = useState(0);
55
+ const result = useQuery({
56
+ queryKey: ["omni-reader", "document", host.id, workspaceId, file.path, file.modifiedAt, generation],
57
+ queryFn: () => rpc({ workspaceId, path: file.path }),
58
+ staleTime: Infinity, gcTime: 30_000, retry: false,
59
+ });
60
+ const sections = result.data?.sections ?? [];
61
+ const index = Math.min(selected, Math.max(0, sections.length - 1));
62
+ const active = sections[index];
63
+ const slides = file.extension === "pptx";
64
+ return (
65
+ <View testID="omni-structured-panel" style={{ flex: 1, minHeight: 0, backgroundColor: theme.colors.surface0 }}>
66
+ <Toolbar theme={theme}>
67
+ <ExternalFileAction {...props} />
68
+ </Toolbar>
69
+ <Text style={{ color: theme.colors.foregroundMuted, paddingHorizontal: 12, paddingVertical: 6 }}>
70
+ {t("officeLayoutUnavailable")}
71
+ </Text>
72
+ {result.isPending && <Loading />}
73
+ {result.isError && (
74
+ <ReadError theme={theme} compact={compact} label={t("textError")} error={result.error}
75
+ retry={t("retry")} onRetry={() => { void result.refetch(); }} />
76
+ )}
77
+ {(sections.length > 1 || slides && !!sections.length) && (
78
+ <ScrollView horizontal style={{ flexGrow: 0 }} contentContainerStyle={{ padding: 4, gap: 4 }}>
79
+ {sections.map((section, sectionIndex) => (
80
+ <Control key={sectionIndex}
81
+ title={(slides ? t("slide") : section.title || t("sheet")) + (slides || !section.title ? ` ${sectionIndex + 1}` : "")}
82
+ onPress={() => setSelected(sectionIndex)} selected={index === sectionIndex} theme={theme} compact={compact} />
83
+ ))}
84
+ </ScrollView>
85
+ )}
86
+ {result.data?.truncated && (
87
+ <Text style={{ color: theme.colors.foregroundMuted, paddingHorizontal: 12, paddingVertical: 6 }}>{t("documentTruncated")}</Text>
88
+ )}
89
+ {active && (active.blocks.length > 0 || active.title && slides) ? (
90
+ <FlatList
91
+ key={index} data={active.blocks} keyExtractor={(_, blockIndex) => String(blockIndex)}
92
+ contentContainerStyle={{ padding: compact ? 16 : 24, gap: 12 }}
93
+ ListHeaderComponent={active.title ? (
94
+ <Text selectable accessibilityRole="header" style={{ color: theme.colors.foreground, fontSize: 24, fontWeight: "600" }}>
95
+ {active.title}
96
+ </Text>
97
+ ) : null}
98
+ renderItem={({ item }) => item.kind === "table" ? <DataTable block={item} theme={theme} />
99
+ : (
100
+ <Text selectable accessibilityRole={item.heading ? "header" : undefined} style={{
101
+ color: theme.colors.foreground, fontSize: item.heading ? 21 : 16,
102
+ lineHeight: item.heading ? 28 : 24, fontWeight: item.heading ? "600" : "400",
103
+ }}>{item.text}</Text>
104
+ )}
105
+ />
106
+ ) : result.data && <Text style={{ padding: 16, color: theme.colors.foregroundMuted }}>{t("empty")}</Text>}
107
+ </View>
108
+ );
109
+ }
@@ -0,0 +1,76 @@
1
+ import { useState } from "react";
2
+ import { Alert, Platform, Share } from "react-native";
3
+ import { useQuery } from "@tanstack/react-query";
4
+ import { useRpc, useTranslation, type PluginFilePanelProps } from "@getpaseo/plugin/client";
5
+ import { copyText, useToast } from "@getpaseo/plugin/client/ui";
6
+ import { openWorkspaceFile } from "../shared/contracts";
7
+ import { shareAndroidFile } from "./android-file-share";
8
+ import { Control } from "./controls";
9
+ import { messages } from "./messages";
10
+ import { downloadLocalFile } from "./web";
11
+
12
+ type DesktopBridge = { invoke(command: "desktop_daemon_status"): Promise<unknown> };
13
+
14
+ async function desktopDaemonId(desktop: DesktopBridge) {
15
+ const status = await desktop.invoke("desktop_daemon_status");
16
+ return typeof status === "object" && status !== null && "status" in status && status.status === "running" &&
17
+ "serverId" in status && typeof status.serverId === "string" ? status.serverId : null;
18
+ }
19
+
20
+ export function ExternalFileAction({ file, workspaceId, host, theme, layout }: PluginFilePanelProps) {
21
+ const { t } = useTranslation(messages);
22
+ const toast = useToast();
23
+ const openLocal = useRpc(openWorkspaceFile);
24
+ const [opening, setOpening] = useState(false);
25
+ const desktop = Platform.OS === "web" && typeof window !== "undefined"
26
+ ? (window as Window & { paseoDesktop?: DesktopBridge }).paseoDesktop
27
+ : undefined;
28
+ const localDaemon = useQuery({
29
+ queryKey: ["omni-reader", "desktop-daemon"],
30
+ queryFn: () => desktopDaemonId(desktop!),
31
+ enabled: typeof desktop?.invoke === "function",
32
+ staleTime: 5_000,
33
+ retry: false,
34
+ });
35
+ const localFile = Boolean(localDaemon.data) && localDaemon.data === host.id;
36
+ const checking = typeof desktop?.invoke === "function" && localDaemon.isPending;
37
+ const download = Platform.OS === "web" && !localFile;
38
+ const showAndroidFallback = () => {
39
+ Alert.alert(t("externalFile"), t("externalAndroid"), [
40
+ { text: t("cancel"), style: "cancel" },
41
+ {
42
+ text: t("copyFilePath"),
43
+ onPress: () => {
44
+ void copyText(file.path).then(() => toast.show(t("copied"), { variant: "success" }),
45
+ () => toast.error(t("externalError")));
46
+ },
47
+ },
48
+ ], { cancelable: true });
49
+ };
50
+ const open = async () => {
51
+ setOpening(true);
52
+ try {
53
+ if (Platform.OS === "android") {
54
+ if (!await shareAndroidFile(file, file.name)) showAndroidFallback();
55
+ return;
56
+ }
57
+ if (localFile) {
58
+ await openLocal({ workspaceId, path: file.path });
59
+ return;
60
+ }
61
+ const url = await file.url();
62
+ if (Platform.OS === "ios" && url.startsWith("file:")) await Share.share({ url });
63
+ else if (Platform.OS === "web") downloadLocalFile(url, file.name);
64
+ else throw new Error("Unsupported file URL.");
65
+ } catch {
66
+ if (Platform.OS === "android") showAndroidFallback();
67
+ else toast.error(t(localFile ? "externalAppError" : download ? "downloadError" : "externalError"));
68
+ } finally {
69
+ setOpening(false);
70
+ }
71
+ };
72
+ return (
73
+ <Control title={t(download ? "downloadFile" : "externalFile")} icon={download ? "Download" : "ExternalLink"}
74
+ theme={theme} compact={layout.compact} disabled={opening || checking} onPress={() => { void open(); }} />
75
+ );
76
+ }
@@ -0,0 +1,134 @@
1
+ import { useCallback, useEffect, useLayoutEffect, useState, type ComponentType, type ReactNode } from "react";
2
+ import { Modal, SafeAreaView, Text, View } from "react-native";
3
+ import { useTranslation, type PluginFilePanelProps } from "@getpaseo/plugin/client";
4
+ import { Icon, Loading } from "@getpaseo/plugin/client/ui";
5
+ import { Control, type Theme } from "./controls";
6
+ import { messages } from "./messages";
7
+ import { createReaderOpenGate } from "./reader-open-gate";
8
+ import { IsolatedReader } from "./reader-scroll";
9
+
10
+ const readerIcon = {
11
+ svg: '<svg viewBox="0 0 24 24"><rect x="1" y="1" width="22" height="22" rx="4" fill="#141052"/><path fill="#f8f4e8" d="M3.5 7C3.5 5.5 9.5 5.8 11.8 8v10c-2.6-1.8-5.1-2-7.7-1.3-.4.1-.6 0-.6-.4zm17 0v9.3c0 .4-.2.5-.6.4-2.6-.7-5.1-.5-7.7 1.3V8c2.3-2.2 8.3-2.5 8.3-1z"/><path fill="#64a386" d="M12.2 8c.4-.4.9-.7 1.4-.9v6.4l-.7-.8-.7.8z"/></svg>',
12
+ };
13
+
14
+ type ReaderTab = PluginFilePanelProps["tab"] & {
15
+ active?: boolean;
16
+ close?: () => void;
17
+ };
18
+
19
+ type Presentation = "initial" | "fullScreen" | "desktop" | "embedded" | "ignored";
20
+
21
+ const claimReaderOpen = createReaderOpenGate();
22
+
23
+ function DesktopReaderBody({ children }: { children: ReactNode }) {
24
+ const [shown, setShown] = useState(false);
25
+ useEffect(() => {
26
+ let frame = requestAnimationFrame(() => {
27
+ frame = requestAnimationFrame(() => setShown(true));
28
+ });
29
+ return () => cancelAnimationFrame(frame);
30
+ }, []);
31
+ return shown ? children : <Loading />;
32
+ }
33
+
34
+ function FullScreenReader({ header, theme, close, children }: {
35
+ header: ReactNode; theme: Theme; close: () => void; children: ReactNode;
36
+ }) {
37
+ const [shown, setShown] = useState(false);
38
+ return (
39
+ <Modal visible presentationStyle="fullScreen" onRequestClose={close} onShow={() => setShown(true)}
40
+ animationType="none" allowSwipeDismissal={false} hardwareAccelerated
41
+ supportedOrientations={["portrait", "landscape"]}>
42
+ <SafeAreaView accessibilityViewIsModal onAccessibilityEscape={close}
43
+ style={{ flex: 1, backgroundColor: theme.colors.surface0 }}>
44
+ <IsolatedReader.Provider value>
45
+ {header}
46
+ {shown ? children : <Loading />}
47
+ </IsolatedReader.Provider>
48
+ </SafeAreaView>
49
+ </Modal>
50
+ );
51
+ }
52
+
53
+ export function fileReader(Reader: ComponentType<PluginFilePanelProps>) {
54
+ function ReaderPresentation({ props, fileKey }: { props: PluginFilePanelProps; fileKey: string }) {
55
+ const { file, layout, tab, theme } = props;
56
+ const { t } = useTranslation(messages);
57
+ const { active, close: closeTab } = tab as ReaderTab;
58
+ const native = layout.platform !== "web";
59
+ const [owner] = useState(() => Symbol());
60
+ const [nativeLayoutReady, setNativeLayoutReady] = useState(false);
61
+ const [presentation, setPresentation] = useState<Presentation>("initial");
62
+ const requestOpen = useCallback(() => {
63
+ if (!claimReaderOpen(fileKey, owner)) return false;
64
+ setPresentation(native ? "fullScreen" : "desktop");
65
+ return true;
66
+ }, [fileKey, native, owner]);
67
+ const canOpen = active !== false && (!native || active === true || nativeLayoutReady);
68
+ useLayoutEffect(() => {
69
+ if (presentation === "initial" && canOpen && !requestOpen()) setPresentation("ignored");
70
+ }, [canOpen, presentation, requestOpen]);
71
+ useEffect(() => {
72
+ if (presentation !== "ignored" || active === false || !closeTab) return;
73
+ const timeout = setTimeout(closeTab, 0);
74
+ return () => clearTimeout(timeout);
75
+ }, [active, closeTab, presentation]);
76
+ const fullScreen = presentation === "fullScreen" && active !== false;
77
+ const awaitNativeLayout = native && active === undefined && presentation === "initial" && !nativeLayoutReady;
78
+ const showClose = fullScreen || (!layout.compact && !!closeTab);
79
+ const close = closeTab ?? (() => setPresentation("embedded"));
80
+ const header = (
81
+ <View testID="omni-reader-header" style={{
82
+ flexDirection: "row", alignItems: "center", gap: 8, minHeight: 32,
83
+ paddingLeft: 12, paddingRight: 4, borderBottomWidth: 1, borderColor: theme.colors.border,
84
+ backgroundColor: theme.colors.surface0,
85
+ }}>
86
+ <Icon icon={readerIcon} size={17} />
87
+ <Text numberOfLines={1} accessibilityRole="header"
88
+ style={{ flex: 1, color: theme.colors.foreground, fontSize: 13 }}>{file.name}</Text>
89
+ {(presentation === "ignored" || (native && presentation === "embedded")) && (
90
+ <Control
91
+ icon={native ? "Maximize" : "BookOpenText"}
92
+ title={t(native ? "fullScreenReader" : "preview")}
93
+ onPress={requestOpen} theme={theme} compact={native}
94
+ />
95
+ )}
96
+ {showClose && (
97
+ <Control icon="X" title={t("closeReader")} onPress={close} theme={theme} compact={native} />
98
+ )}
99
+ </View>
100
+ );
101
+ if (awaitNativeLayout) {
102
+ return (
103
+ <View collapsable={false} style={{ flex: 1, minHeight: 0, backgroundColor: theme.colors.surface0 }}
104
+ onLayout={({ nativeEvent: { layout: bounds } }) => {
105
+ if (bounds.width > 0 && bounds.height > 0) {
106
+ setNativeLayoutReady(true);
107
+ }
108
+ }} />
109
+ );
110
+ }
111
+ if (fullScreen) {
112
+ return (
113
+ <FullScreenReader {...{ header, theme, close }}>
114
+ <Reader key={file.path} {...props} />
115
+ </FullScreenReader>
116
+ );
117
+ }
118
+ return (
119
+ <View style={{ flex: 1, minHeight: 0, backgroundColor: theme.colors.surface0 }}>
120
+ {header}
121
+ {presentation === "desktop" && (
122
+ <DesktopReaderBody key={file.path}>
123
+ <Reader {...props} />
124
+ </DesktopReaderBody>
125
+ )}
126
+ </View>
127
+ );
128
+ }
129
+
130
+ return function OmniFileReader(props: PluginFilePanelProps) {
131
+ const fileKey = JSON.stringify([props.host.id, props.workspaceId, props.file.path]);
132
+ return <ReaderPresentation key={fileKey} props={props} fileKey={fileKey} />;
133
+ };
134
+ }