mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-23 16:55:42 +00:00
Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a796e760e9 | ||
|
|
47bcf6e609 | ||
|
|
5b82167872 | ||
|
|
9e1b53c4e9 | ||
|
|
8a892ed4a7 | ||
|
|
40c5accf2a | ||
|
|
4d472c2804 | ||
|
|
182c1aa192 | ||
|
|
8fa709532c | ||
|
|
6e4f2ef8da | ||
|
|
34abe8f08f | ||
|
|
3389138eb7 | ||
|
|
eedb6ff675 | ||
|
|
cd66d8fd18 | ||
|
|
a48e9edce5 | ||
|
|
df9886b2f1 | ||
|
|
8fa22b39eb | ||
|
|
80c44321cc | ||
|
|
576b9b552b | ||
|
|
175d858e05 | ||
|
|
112c4b78e1 | ||
|
|
8d287e5f56 | ||
|
|
ec22b82659 | ||
|
|
02e7b10648 | ||
|
|
3e4f67d88f | ||
|
|
e886aebff3 | ||
|
|
f596e3f7aa |
@@ -50,6 +50,7 @@ desktop:
|
||||
app:
|
||||
- "packages/app/**"
|
||||
- "packages/expo-two-way-audio/**"
|
||||
- "packages/react-native-enriched-markdown/**"
|
||||
|
||||
sdk:
|
||||
- "packages/plugin/**"
|
||||
@@ -80,6 +81,7 @@ browser:
|
||||
- "packages/app/index.ts"
|
||||
- "packages/app/*config.{cjs,js,ts}"
|
||||
- "packages/app/package.json"
|
||||
- "packages/react-native-enriched-markdown/**"
|
||||
|
||||
relay:
|
||||
- "packages/relay/**"
|
||||
|
||||
@@ -299,10 +299,7 @@ jobs:
|
||||
run: npm run test:integration --workspace=@getpaseo/server
|
||||
env: *server_test_env
|
||||
|
||||
# native-recursive.ts serves darwin and win32, but windows-latest above is the only
|
||||
# runner that exercises it. macOS — the platform the reported watcher bug was on —
|
||||
# otherwise has no server-test coverage. Keep this job scoped to regressions
|
||||
# reported on macOS.
|
||||
# Keep this job scoped to regressions reported on macOS.
|
||||
server-tests-macos:
|
||||
name: server-tests (macos-latest, file observation)
|
||||
needs: changes
|
||||
@@ -330,12 +327,24 @@ jobs:
|
||||
src/server/workspace-git-service.observation.integration.test.ts \
|
||||
--bail=1
|
||||
|
||||
- name: Verify path casing on macOS
|
||||
run: |
|
||||
npm run test:unit --workspace=@getpaseo/server -- \
|
||||
src/server/agent/agent-storage.test.ts \
|
||||
src/utils/directory-suggestions.test.ts \
|
||||
--bail=1
|
||||
|
||||
- name: Verify plugin compiler children are reaped
|
||||
run: |
|
||||
npm run test:unit --workspace=@getpaseo/server -- \
|
||||
src/server/plugins/index.posix.test.ts \
|
||||
-t "reaps compiler children" --bail=1
|
||||
|
||||
- name: Verify plugin session sockets survive a dead plugin child
|
||||
run: |
|
||||
npm run test:unit --workspace=@getpaseo/server -- \
|
||||
src/server/plugins/session-socket.posix.test.ts --bail=1
|
||||
|
||||
desktop-tests-ubuntu:
|
||||
name: desktop-tests (ubuntu-latest)
|
||||
needs: changes
|
||||
|
||||
+6
-1
@@ -11,5 +11,10 @@
|
||||
"arrowParens": "always",
|
||||
"bracketSameLine": false,
|
||||
"bracketSpacing": true,
|
||||
"ignorePatterns": ["*.lock", "**/*.gen.ts", "**/*.gen.tsx"]
|
||||
"ignorePatterns": [
|
||||
"*.lock",
|
||||
"**/*.gen.ts",
|
||||
"**/*.gen.tsx",
|
||||
"packages/react-native-enriched-markdown/**"
|
||||
]
|
||||
}
|
||||
|
||||
+1
-2
@@ -3,7 +3,7 @@
|
||||
"options": {
|
||||
"typeAware": false
|
||||
},
|
||||
"ignorePatterns": [".dev/**"],
|
||||
"ignorePatterns": [".dev/**", "packages/react-native-enriched-markdown/**"],
|
||||
"plugins": ["react", "react-perf", "unicorn", "typescript", "oxc", "import", "promise"],
|
||||
"jsPlugins": ["./scripts/oxlint/paseo-plugin.mjs"],
|
||||
"categories": {
|
||||
@@ -552,7 +552,6 @@
|
||||
"packages/app/src/components/download-toast.tsx",
|
||||
"packages/app/src/components/file-explorer-pane.tsx",
|
||||
"packages/app/src/components/headers/back-header.tsx",
|
||||
"packages/app/src/components/highlighted-code-block.tsx",
|
||||
"packages/app/src/components/hosts/host-filter.tsx",
|
||||
"packages/app/src/components/hosts/host-picker.tsx",
|
||||
"packages/app/src/components/import-session-sheet.tsx",
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# Changelog
|
||||
|
||||
## 0.17.3 - 2026-11-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed iPhone sheets such as Workspace tabs ignoring body swipes to expand, scroll, or collapse ([#10525](https://github.com/getpaseo/paseo/pull/10525))
|
||||
- Fixed Antigravity applying the default model's thinking levels to every model, which blocked Orchestrator chats from opening ([#10524](https://github.com/getpaseo/paseo/pull/10524))
|
||||
- Fixed `/` and `@` pickers disappearing until reload after returning to a workspace through window history ([#8954](https://github.com/getpaseo/paseo/pull/8954) by [@viking1201](https://github.com/viking1201))
|
||||
|
||||
## 0.17.2 - 2026-11-22
|
||||
|
||||
- **Turn and session stats:** View per-turn and session timing, token, cache, and cost metrics for Claude, OpenCode v2, Pi, Oh My Pi, and plugin providers. ([#10496](https://github.com/getpaseo/paseo/pull/10496), [#10510](https://github.com/getpaseo/paseo/pull/10510))
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# Changelog
|
||||
|
||||
## 0.17.3 - 2026-11-22
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复 iPhone 上“Workspace 标签”等弹窗忽略主体滑动、无法展开、滚动或收起的问题 ([#10525](https://github.com/getpaseo/paseo/pull/10525))
|
||||
- 修复 Antigravity 将默认模型的思考级别套用到所有模型,导致无法打开 Orchestrator 对话的问题 ([#10524](https://github.com/getpaseo/paseo/pull/10524))
|
||||
- 修复通过窗口历史记录返回工作区后,`/` 和 `@` 选择器在刷新前一直消失的问题 ([#8954](https://github.com/getpaseo/paseo/pull/8954),贡献者:[@viking1201](https://github.com/viking1201))
|
||||
|
||||
## 0.17.2 - 2026-11-22
|
||||
|
||||
- **回合和会话统计**:查看 Claude、OpenCode v2、Pi、Oh My Pi 和插件 Provider 的单轮及会话耗时、token、缓存和费用指标。([#10496](https://github.com/getpaseo/paseo/pull/10496), [#10510](https://github.com/getpaseo/paseo/pull/10510))
|
||||
|
||||
@@ -56,7 +56,7 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
|
||||
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
|
||||
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
|
||||
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, native selection, links, images and library constraints |
|
||||
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
|
||||
| [docs/native-text-selection.md](docs/native-text-selection.md) | Native diagram grouping, selection boundaries and leading inline image limitations |
|
||||
| [docs/file-observation.md](docs/file-observation.md) | Recursive watcher ownership, Linux constraints, teardown invariants, and Parcel comparison |
|
||||
| [docs/testing.md](docs/testing.md) | TDD workflow, determinism, real dependencies over mocks, test organization |
|
||||
|
||||
@@ -121,6 +121,12 @@ from `packages/app/android`:
|
||||
|
||||
These check terminal arrow ownership, held-key repeats and modifiers, and ordinary text-field editing.
|
||||
|
||||
Run the terminal module's tests the same way with `:paseo-terminal:connectedDebugAndroidTest`. Besides
|
||||
row layout, they check that the terminal input asks the keyboard not to learn what is typed
|
||||
(`IME_FLAG_NO_PERSONALIZED_LEARNING`), so passwords typed at a prompt stay out of Gboard's
|
||||
suggestions in other apps. React Native's TextInput has no prop for that flag, and it replaces
|
||||
`imeOptions` when `returnKeyType` or `disableFullscreenUI` is set, so the terminal input sets neither.
|
||||
|
||||
Run the display density regression tests the same way:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -14,19 +14,42 @@ Workspace file links use the shared file-link resolver. The workspace supplies i
|
||||
|
||||
Pass `external` for author-controlled Markdown from outside the host, such as a plugin README. It follows the registry's overview contract in `packages/protocol/src/plugin-overview.ts`, which the website also uses: only absolute https links and images work, and any other destination renders as its label or alt text. The parser still autolinks bare `http://`, `www.` and email text, so a link press checks the URL again and opens only https. None of the workspace recognition above applies, so `Node.js` is prose, not a file. The lines of a paragraph join, as they do on the README's forge.
|
||||
|
||||
Resolve workspace image paths over the existing session RPC, then give the library a cached native file URL or web blob URL. HTTP(S) images pass through unchanged. This preserves relay, SSH and local socket connections, which do not expose a daemon HTTP endpoint. Each mounted renderer owns its image acquisition identity, so a later reply reads a rewritten path again while the earlier mounted reply retains its snapshot. Image taps open the attachment lightbox. File previews resolve relative images against the Markdown file's directory. An image alone on its line becomes its own paragraph before the library sees it, so it renders as a block on every platform; the library only treats sole-child paragraph images as blocks, and with hard soft breaks every newline is a break node, which left own-line images inline on iOS and web. Images that share a line with text stay inline at line height and keep their aspect ratio. A linked image counts as an image, so review-bot badges such as `[](url) Confidence` stay inline on web; the library's web renderer only checked direct paragraph children, so it rendered them as full-width block images (local patch in `patches/react-native-enriched-markdown+*.patch`).
|
||||
Resolve workspace image paths over the existing session RPC, then give the library a cached native file URL or web blob URL. HTTP(S) images pass through unchanged. This preserves relay, SSH and local socket connections, which do not expose a daemon HTTP endpoint. Each mounted renderer owns its image acquisition identity, so a later reply reads a rewritten path again while the earlier mounted reply retains its snapshot. Image taps open the attachment lightbox. File previews resolve relative images against the Markdown file's directory. An image alone on its line becomes its own paragraph before the library sees it, so it renders as a block on every platform; the library only treats sole-child paragraph images as blocks, and with hard soft breaks every newline is a break node, which left own-line images inline on iOS and web. Images that share a line with text stay inline at line height and keep their aspect ratio. A linked image counts as an image, so review-bot badges such as `[](url) Confidence` stay inline on web; the library's web renderer only checked direct paragraph children, so it rendered them as full-width block images (fixed in the fork).
|
||||
|
||||
## The fork
|
||||
|
||||
The library is a private workspace, `packages/react-native-enriched-markdown`. It is upstream [enriched-markdown](https://github.com/software-mansion/enriched-markdown) at npm `1.2.0-nightly-20261014-766fc0e67` (upstream commit `766fc0e67`) plus Paseo's changes, which lived in a `patch-package` patch until the package moved into the repository. It is never published. Keep the name `react-native-enriched-markdown`: autolinking, the Gradle project `:react-native-enriched-markdown`, the CocoaPods spec and app imports all use it.
|
||||
|
||||
The package keeps the npm tarball's layout, including its build output:
|
||||
|
||||
- Metro, Vitest and TypeScript load `lib/`, not `src/`. A JavaScript change edits `src/` and the matching `lib/module` and `lib/typescript` files.
|
||||
- `android/generated` and `ios/generated` are checked-in codegen output (`includesGeneratedCode`). A change to a native component spec regenerates both; `scripts/postinstall-patches.test.mjs` compares them against the specs.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`. A parser change rebuilds them with upstream's `packages/core/cpp/wasm/build.sh`.
|
||||
- Upstream's Gradle, CMake and CocoaPods scripts detect upstream's own monorepo by the paths `packages/core` and a root `vendor/`. Do not add either path to this repository.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
|
||||
|
||||
CI does not build native code or run the fork's Robolectric suites. Run `npm run test:android --workspace=@getpaseo/app` for Android changes. Native changes require a client rebuild; JavaScript refresh cannot enable compiled grammars.
|
||||
|
||||
Some fork changes are backports. A sync past the upstream version drops them in favour of upstream's code:
|
||||
|
||||
| Fork change | Upstream | Released in |
|
||||
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------- |
|
||||
| Android measurements survive parent clones | [#924](https://github.com/software-mansion/enriched-markdown/pull/924) | after `1.2.0-nightly-20261019-926ef06f0` |
|
||||
| Android nested list items start their text after their own marker | [#1015](https://github.com/software-mansion/enriched-markdown/pull/1015), [#1023](https://github.com/software-mansion/enriched-markdown/pull/1023) (Android) | `1.2.0` |
|
||||
|
||||
## Engine constraints
|
||||
|
||||
The pinned nightly has the same React Native package and core source trees as upstream commit `73ac5085eb1fdc743973b3473d4dba65abad5261`. Compatibility was checked with React Native 0.81.5. Native dependencies must be rebuilt when changing the highlighting configuration; JavaScript refresh cannot enable compiled grammars.
|
||||
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded.
|
||||
|
||||
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
|
||||
|
||||
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The patch also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. The package patch is tracked by [upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997); remove the patch when the pinned release includes it.
|
||||
Code blocks and plain quotes have a copy control in their top trailing corner. Native code blocks use the library's compiled grammars. On native, the code block and quote container views share one control (`HeaderCopyButton` on Android, `ENRMHeaderCopyButton` on iOS). A quote reserves the code block's header band above its body, so the control never covers quote text at any font size. On web, code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override, and quotes use `WebBlockquote` through `renderers.blockquote`. Both use `BlockCopyButton`. On compact layouts the control is always visible, so the web quote reserves a band above its body, as native does. On wide layouts the control appears on hover or focus, so the quote keeps a right gutter instead; a band there would leave an empty strip above every quote.
|
||||
|
||||
The package patch also keeps overflowing native horizontal blocks in control of their drags: Android claims parent interception at touch-down and releases it for vertical drags so the chat list can scroll; iOS keeps its scroll recognizer active for outward drags at the leading edge. This prevents compact sidebar pans from taking block scrolling without changing sidebar swipes on prose or non-overflowing blocks. Native changes require a client rebuild.
|
||||
A quote copies its body without the `>` markers, with its nested Markdown, and reads the content at the time of the press, so a streaming quote copies what it shows. A nested quote or code block keeps its own control. Web quote copy uses the same two clipboard flavors as selection copy: `text/plain` is unescaped Markdown and `text/html` is rendered from escaped Markdown. A rendered Mermaid diagram copies as its fence because its wrapper carries the fence source. Native quote copy serializes the quote's parsed Markdown, so a workspace image copies as its cached file URL, as native selection copy does; native has no map back to the workspace path. A native Mermaid diagram in a quote renders outside it (see [native selection limitations](native-text-selection.md)), so each quote fragment copies only its own text. Admonitions get no control: web renders them with a separate library renderer. On web an admonition inside a copied quote copies as its `> [!TYPE]` source; the fork marks the box and its generated title for this. Selection copy keeps the text it shows, because the cloned range cannot tell a whole callout from part of one. On native, quotes inside list items get no control, because they render as text spans in the item. Web renders them as blocks, so they get one.
|
||||
|
||||
Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
|
||||
|
||||
The fork also keeps overflowing native horizontal blocks in control of their drags: Android claims parent interception at touch-down and releases it for vertical drags so the chat list can scroll; iOS keeps its scroll recognizer active for outward drags at the leading edge. This prevents compact sidebar pans from taking block scrolling without changing sidebar swipes on prose or non-overflowing blocks. Native changes require a client rebuild.
|
||||
|
||||
On iOS a newly mounted Markdown view paints empty for a frame or more after it is laid out at its measured height: the library parses even a view's first content on a background queue and applies it in a later main-queue turn. Expanding a turn in chat therefore shows its rows in place with the text arriving a frame later (165 ms when the mount keeps the main thread busy). Android paints the text in the first frame. Rendering a view's first content synchronously fixes the frame but costs frame time when a fling mounts history rows, so the app keeps the library's behavior until [enriched-markdown #1131](https://github.com/software-mansion/enriched-markdown/issues/1131) is resolved.
|
||||
|
||||
@@ -36,4 +59,4 @@ The library determines how incomplete Markdown appears during streaming. Complet
|
||||
|
||||
## Verification
|
||||
|
||||
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
|
||||
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, quote copy (nested quote, code block in a quote, admonition, large font on native), a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed iPhone sheets such as Workspace tabs ignoring body swipes to expand, scroll, or collapse
|
||||
- Fixed Antigravity applying the default model's thinking levels to every model, which blocked Orchestrator chats from opening
|
||||
- Fixed / and @ pickers disappearing until reload after returning to a workspace through window history
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed iPhone sheets such as Workspace tabs ignoring body swipes to expand, scroll, or collapse
|
||||
- Fixed Antigravity applying the default model's thinking levels to every model, which blocked Orchestrator chats from opening
|
||||
- Fixed / and @ pickers disappearing until reload after returning to a workspace through window history
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed iPhone sheets such as Workspace tabs ignoring body swipes to expand, scroll, or collapse
|
||||
- Fixed Antigravity applying the default model's thinking levels to every model, which blocked Orchestrator chats from opening
|
||||
- Fixed / and @ pickers disappearing until reload after returning to a workspace through window history
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -0,0 +1,6 @@
|
||||
Fixed
|
||||
- Fixed iPhone sheets such as Workspace tabs ignoring body swipes to expand, scroll, or collapse
|
||||
- Fixed Antigravity applying the default model's thinking levels to every model, which blocked Orchestrator chats from opening
|
||||
- Fixed / and @ pickers disappearing until reload after returning to a workspace through window history
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
@@ -72,6 +72,7 @@
|
||||
"project": ["src/**/*.ts"]
|
||||
}
|
||||
},
|
||||
"ignoreWorkspaces": ["packages/react-native-enriched-markdown"],
|
||||
"ignoreDependencies": [
|
||||
"sherpa-onnx-node",
|
||||
"@playwright/test",
|
||||
|
||||
@@ -30,6 +30,8 @@ buildNpmPackage {
|
||||
# Exclude mobile-only platform code (we only need the web/electron build)
|
||||
!(lib.hasPrefix "/packages/app/android" relPath)
|
||||
&& !(lib.hasPrefix "/packages/app/ios" relPath)
|
||||
&& !(lib.hasPrefix "/packages/react-native-enriched-markdown/android" relPath)
|
||||
&& !(lib.hasPrefix "/packages/react-native-enriched-markdown/ios" relPath)
|
||||
# Website is unrelated to the desktop app
|
||||
&& !(lib.hasPrefix "/packages/website" relPath)
|
||||
# Documentation, CI definitions and agent/editor configuration. None of
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-vtzoUMnKaAdBFd/hhnk9p2WwHGgL70RXh26vkkyRIH0=
|
||||
sha256-W725BRG14xajMsR4t8Y3NmxppMnJ8AUd7Kdb6F7LmMw=
|
||||
|
||||
Generated
+114
-49
@@ -1,17 +1,18 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "paseo",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
"plugins",
|
||||
"packages/expo-two-way-audio",
|
||||
"packages/react-native-enriched-markdown",
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
@@ -8519,6 +8520,52 @@
|
||||
"integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==",
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/client": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.4.0.tgz",
|
||||
"integrity": "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/core": "2.4.0",
|
||||
"cross-spawn": "^7.0.5",
|
||||
"eventsource": "^3.0.2",
|
||||
"eventsource-parser": "^3.0.8",
|
||||
"jose": "^6.1.3",
|
||||
"pkce-challenge": "^5.0.0",
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/core": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz",
|
||||
"integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==",
|
||||
"dependencies": {
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/node": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/node/-/node-2.1.2.tgz",
|
||||
"integrity": "sha512-IIcIqBpr6NCQQs5DgJTgvbSOAw+3iaR/uquqg+e0nXCdudfjPg/80x0TseUnQx14AUAtE4fsJCEpJKPyb6WPVA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@hono/node-server": "^1.19.9 || ^2.1.3",
|
||||
"hono": "^4.11.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@modelcontextprotocol/server": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/sdk": {
|
||||
"version": "1.29.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",
|
||||
@@ -8905,6 +8952,19 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/server": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.4.0.tgz",
|
||||
"integrity": "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/core": "2.4.0",
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.4.tgz",
|
||||
@@ -20578,9 +20638,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/eventsource-parser": {
|
||||
"version": "3.0.6",
|
||||
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz",
|
||||
"integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
|
||||
"integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
@@ -31902,6 +31962,10 @@
|
||||
"react-native": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/react-native-enriched-markdown": {
|
||||
"resolved": "packages/react-native-enriched-markdown",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/react-native-gesture-handler": {
|
||||
"version": "2.32.0",
|
||||
"resolved": "https://registry.npmjs.org/react-native-gesture-handler/-/react-native-gesture-handler-2.32.0.tgz",
|
||||
@@ -37477,7 +37541,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -37561,7 +37625,7 @@
|
||||
"react-native": "0.86.3",
|
||||
"react-native-draggable-flatlist": "^4.0.3",
|
||||
"react-native-edge-to-edge": "^1.7.0",
|
||||
"react-native-enriched-markdown": "1.2.0-nightly-20261014-766fc0e67",
|
||||
"react-native-enriched-markdown": "*",
|
||||
"react-native-gesture-handler": "~2.32.0",
|
||||
"react-native-keyboard-controller": "1.21.12",
|
||||
"react-native-nitro-modules": "0.35.5",
|
||||
@@ -39474,23 +39538,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"packages/app/node_modules/react-native-enriched-markdown": {
|
||||
"version": "1.2.0-nightly-20261014-766fc0e67",
|
||||
"resolved": "https://registry.npmjs.org/react-native-enriched-markdown/-/react-native-enriched-markdown-1.2.0-nightly-20261014-766fc0e67.tgz",
|
||||
"integrity": "sha512-PyYAAVJAyjlcqHXgSnzxok13MDmyxs/nt46hHIOBdCc0prfaL2Ef6nYkZu7fFCeaETOJXd/xQr4n2/79I+gvdA==",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"katex": ">=0.16.0",
|
||||
"react": "*",
|
||||
"react-native": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"katex": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"packages/app/node_modules/react-native-keyboard-controller": {
|
||||
"version": "1.21.12",
|
||||
"resolved": "https://registry.npmjs.org/react-native-keyboard-controller/-/react-native-keyboard-controller-1.21.12.tgz",
|
||||
@@ -39647,13 +39694,13 @@
|
||||
},
|
||||
"packages/cli": {
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.17.2",
|
||||
"@getpaseo/protocol": "0.17.2",
|
||||
"@getpaseo/server": "0.17.2",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/server": "0.17.3",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
@@ -39900,11 +39947,11 @@
|
||||
},
|
||||
"packages/client": {
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.17.2",
|
||||
"@getpaseo/relay": "0.17.2",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/relay": "0.17.3",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -39916,7 +39963,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
@@ -40159,7 +40206,7 @@
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
@@ -40205,7 +40252,7 @@
|
||||
},
|
||||
"packages/highlight": {
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "6.12.4",
|
||||
@@ -40235,7 +40282,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^1.4.0",
|
||||
@@ -40243,8 +40290,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.17.2",
|
||||
"@getpaseo/protocol": "0.17.2",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -40254,8 +40301,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.17.2",
|
||||
"@getpaseo/protocol": "0.17.2",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
@@ -40277,7 +40324,7 @@
|
||||
},
|
||||
"packages/protocol": {
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"semver": "^7.8.5",
|
||||
@@ -40303,9 +40350,24 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"packages/react-native-enriched-markdown": {
|
||||
"version": "0.17.1",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"katex": ">=0.16.0",
|
||||
"react": "*",
|
||||
"react-native": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"katex": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"packages/relay": {
|
||||
"name": "@getpaseo/relay",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "^2.4.0",
|
||||
@@ -40527,19 +40589,21 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@getpaseo/server",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.17.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.326",
|
||||
"@anthropic-ai/sdk": "^0.104.2",
|
||||
"@getpaseo/client": "0.17.2",
|
||||
"@getpaseo/highlight": "0.17.2",
|
||||
"@getpaseo/plugin": "0.17.2",
|
||||
"@getpaseo/protocol": "0.17.2",
|
||||
"@getpaseo/relay": "0.17.2",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/highlight": "0.17.3",
|
||||
"@getpaseo/plugin": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/relay": "0.17.3",
|
||||
"@isaacs/ttlcache": "^2.1.4",
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/sdk": "1.29.0",
|
||||
"@modelcontextprotocol/server": "2.4.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
"@opencode/client": "2.0.10",
|
||||
"@xterm/addon-serialize": "0.14.0",
|
||||
@@ -40578,6 +40642,7 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/client": "2.4.0",
|
||||
"@playwright/test": "^1.56.1",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/markdown-it": "^14.2.0",
|
||||
@@ -41484,7 +41549,7 @@
|
||||
},
|
||||
"packages/website": {
|
||||
"name": "@getpaseo/website",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.29.1",
|
||||
"@cloudflare/workers-types": "^4.20260317.1",
|
||||
@@ -43095,7 +43160,7 @@
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"dependencies": {
|
||||
"@getpaseo/plugin": "*",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "paseo",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"private": true,
|
||||
"description": "Paseo: voice-controlled development environment for local AI coding agents",
|
||||
"keywords": [
|
||||
@@ -23,6 +23,7 @@
|
||||
"workspaces": [
|
||||
"plugins",
|
||||
"packages/expo-two-way-audio",
|
||||
"packages/react-native-enriched-markdown",
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
|
||||
@@ -757,6 +757,161 @@ test("pasting an assistant selection preserves literal underscores and authored
|
||||
}
|
||||
});
|
||||
|
||||
const QUOTE_BODY = [
|
||||
"Draft for the team: **ship it** with [the notes](https://example.com/notes).",
|
||||
"",
|
||||
"> Nested reply.",
|
||||
"",
|
||||
"```ts",
|
||||
"const quoted = 1;",
|
||||
"```",
|
||||
"",
|
||||
"```mermaid",
|
||||
"flowchart LR",
|
||||
" Start --> Done",
|
||||
"```",
|
||||
"",
|
||||
"Thanks!",
|
||||
].join("\n");
|
||||
|
||||
const QUOTE_MARKDOWN = [
|
||||
"Text before the quote.",
|
||||
"",
|
||||
...QUOTE_BODY.split("\n").map((line) => (line ? `> ${line}` : ">")),
|
||||
"",
|
||||
"> [!NOTE]",
|
||||
"> Heads up before you paste.",
|
||||
"",
|
||||
"Text after the quote.",
|
||||
].join("\n");
|
||||
|
||||
function assistantQuote(page: Page, index: number): Locator {
|
||||
return assistantMessageBlocks(page).getByRole("blockquote").nth(index);
|
||||
}
|
||||
|
||||
/** A quote's own control is its first, ahead of any nested quote's. */
|
||||
function quoteCopyControl(quote: Locator): Locator {
|
||||
return quote.getByRole("button", { name: "Copy quote" }).first();
|
||||
}
|
||||
|
||||
async function copyQuote(quote: Locator): Promise<void> {
|
||||
await quote.hover();
|
||||
await quoteCopyControl(quote).click();
|
||||
await expect(quote.getByRole("button", { name: "Copied" })).toBeVisible();
|
||||
}
|
||||
|
||||
async function pasteIntoPlainAndRichFields(page: Page): Promise<{ plain: Locator; rich: Locator }> {
|
||||
await page.evaluate(() => {
|
||||
const fields = document.createElement("div");
|
||||
fields.style.cssText = "position: fixed; bottom: 0; left: 0; z-index: 10000; background: white";
|
||||
const plainText = document.createElement("textarea");
|
||||
plainText.setAttribute("aria-label", "Plain text paste");
|
||||
const richText = document.createElement("div");
|
||||
richText.contentEditable = "true";
|
||||
richText.setAttribute("role", "textbox");
|
||||
richText.setAttribute("aria-label", "Rich text paste");
|
||||
fields.append(plainText, richText);
|
||||
document.body.append(fields);
|
||||
});
|
||||
const plain = page.getByRole("textbox", { name: "Plain text paste" });
|
||||
await plain.focus();
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
const rich = page.getByRole("textbox", { name: "Rich text paste" });
|
||||
await rich.focus();
|
||||
await page.keyboard.press("ControlOrMeta+v");
|
||||
return { plain, rich };
|
||||
}
|
||||
|
||||
test("a quote's copy control copies only that quote's body", async ({ context, page }) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "assistant-quote-copy-",
|
||||
title: "Assistant quote copy",
|
||||
initialPrompt: "Render the quote fixture.",
|
||||
featureValues: { mockAssistantResponse: QUOTE_MARKDOWN },
|
||||
});
|
||||
|
||||
try {
|
||||
await allowRichClipboard(context);
|
||||
await agent.client.waitForAgentUpsert(
|
||||
agent.agentId,
|
||||
(snapshot) => snapshot.status === "idle",
|
||||
30_000,
|
||||
);
|
||||
await openAgentRoute(page, agent);
|
||||
const quote = assistantQuote(page, 0);
|
||||
const nested = assistantQuote(page, 1);
|
||||
await expect(quote).toContainText("Thanks!");
|
||||
|
||||
await test.step("an admonition has no copy control", async () => {
|
||||
await expect(assistantMessageBlocks(page)).toContainText("Heads up before you paste.");
|
||||
await expect(
|
||||
assistantMessageBlocks(page).getByRole("button", { name: "Copy quote" }),
|
||||
).toHaveCount(2);
|
||||
});
|
||||
|
||||
await test.step("the control appears on hover or keyboard focus", async () => {
|
||||
const control = quoteCopyControl(quote);
|
||||
await expect(control).toHaveCSS("opacity", "0");
|
||||
await quote.hover();
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
await page.mouse.move(0, 0);
|
||||
await expect(control).toHaveCSS("opacity", "0");
|
||||
await control.focus();
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
await control.blur();
|
||||
});
|
||||
|
||||
await test.step("copying the quote takes its body, with a diagram as its fence", async () => {
|
||||
await expect(quote.getByRole("img", { name: "Diagram" })).toBeVisible({ timeout: 30_000 });
|
||||
await copyQuote(quote);
|
||||
const copied = await readRichClipboard(page);
|
||||
expect(copied.plainText).toBe(QUOTE_BODY);
|
||||
expect(copied.html).toContain("<strong>ship it</strong>");
|
||||
expect(copied.html).toContain("<blockquote>");
|
||||
});
|
||||
|
||||
await test.step("the copy pastes as Markdown and as rich text", async () => {
|
||||
const { plain, rich } = await pasteIntoPlainAndRichFields(page);
|
||||
await expect(plain).toHaveValue(QUOTE_BODY);
|
||||
await expect(rich.locator("strong")).toHaveText("ship it");
|
||||
await expect(rich.getByRole("link", { name: "the notes" })).toHaveAttribute(
|
||||
"href",
|
||||
"https://example.com/notes",
|
||||
);
|
||||
await expect(rich).not.toContainText("Text before the quote.");
|
||||
});
|
||||
|
||||
await test.step("a nested quote copies only itself", async () => {
|
||||
await copyQuote(nested);
|
||||
await expect
|
||||
.poll(async () => (await readRichClipboard(page)).plainText)
|
||||
.toBe("Nested reply.");
|
||||
});
|
||||
|
||||
await test.step("a code block in the quote keeps its own copy", async () => {
|
||||
const code = quote.getByText("const quoted = 1;", { exact: true });
|
||||
await code.hover();
|
||||
await quote.getByRole("button", { name: "Copy code" }).first().click();
|
||||
await expect.poll(() => readPlainClipboard(page)).toBe("const quoted = 1;");
|
||||
});
|
||||
|
||||
await test.step("a phone-sized layout shows the control above the full-width text", async () => {
|
||||
await page.mouse.move(0, 0);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const control = quoteCopyControl(quote);
|
||||
await expect(control).toHaveCSS("opacity", "1");
|
||||
const controlBox = await control.boundingBox();
|
||||
const firstLine = await quote.getByText(/^Draft for the team/).boundingBox();
|
||||
expect(controlBox && firstLine).toBeTruthy();
|
||||
// The text starts below the control instead of wrapping short of it.
|
||||
expect(firstLine!.y).toBeGreaterThanOrEqual(controlBox!.y + controlBox!.height);
|
||||
expect(firstLine!.x + firstLine!.width).toBeGreaterThan(controlBox!.x);
|
||||
});
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("copying a selection across an assistant image keeps its Markdown source and alt text", async ({
|
||||
context,
|
||||
page,
|
||||
|
||||
@@ -64,6 +64,11 @@ import {
|
||||
expectSettingsHostPickerLabel,
|
||||
openSettingsHostSection,
|
||||
removeCurrentHostFromSettings,
|
||||
openSidebarHostPicker,
|
||||
sidebarHostSettingsButton,
|
||||
expectStandaloneSidebarHostSettingsButton,
|
||||
activateSidebarHostSettingsWithKeyboard,
|
||||
bindCommandCenterToEnter,
|
||||
} from "../support/helpers/settings";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { expectAppRoute } from "../support/helpers/route-assertions";
|
||||
@@ -187,6 +192,26 @@ test.describe("Settings sidebar scroll position", () => {
|
||||
});
|
||||
|
||||
test.describe("Settings sidebar navigation", () => {
|
||||
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
|
||||
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
|
||||
await openWorkspace(page, workspace);
|
||||
await openSidebarHostPicker(page);
|
||||
await expectStandaloneSidebarHostSettingsButton(page);
|
||||
await sidebarHostSettingsButton(page).click();
|
||||
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
|
||||
});
|
||||
|
||||
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
|
||||
await bindCommandCenterToEnter(page);
|
||||
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
|
||||
await openWorkspace(page, workspace);
|
||||
await openSidebarHostPicker(page);
|
||||
await activateSidebarHostSettingsWithKeyboard(page);
|
||||
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
|
||||
});
|
||||
|
||||
test("opening Settings closes the composer model selector until it is opened again", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# Tab switcher sheet drag on iPhone
|
||||
|
||||
Run on a task-owned iPhone 17 simulator (402×874 points, portrait) with the development bundle loaded and a connected isolated host. Select a workspace whose first tab is an agent and whose next 11 tabs are terminals, and select the agent tab. Dismiss the notification entitlement toast.
|
||||
|
||||
The sheet exposes its rows to XCUITest as one "Bottom Sheet" element, so the flow taps fixed points and asserts which tab opens. The sheet opens at 60%, where its handle is at y=350, and expands to 90%, where its handle is at y=87.
|
||||
|
||||
1. A swipe up on the list must expand the sheet. The tap at y=300 then lands on the fourth row and opens a terminal. Without the expansion it lands on the backdrop, and no terminal opens.
|
||||
2. A swipe down on the list at 90% must collapse the sheet. The tap at y=424 then lands on the first row and opens the agent. Without the collapse it lands on the sixth row, which is a terminal.
|
||||
|
||||
The flow ends on the agent tab, so you can replay it. Replay it on the Namespace Mac with an explicit device:
|
||||
|
||||
```sh
|
||||
agent-device replay packages/app/e2e/mobile/agent-device/native-tab-switcher-sheet-drag.ios.ad --platform ios --device 'iPhone 17'
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
context platform=ios timeout=60000 retries=0
|
||||
env APP_ID=sh.paseo.debug
|
||||
|
||||
open "${APP_ID}"
|
||||
wait "id=\"agent-chat-scroll\"" 20000
|
||||
press "id=\"workspace-tab-switcher-trigger\""
|
||||
wait "label=\"Bottom Sheet\"" 10000
|
||||
gesture pan 200 650 0 -300 500
|
||||
wait 1000
|
||||
press 200 300
|
||||
wait "id=\"terminal-surface\"" 10000
|
||||
press "id=\"workspace-tab-switcher-trigger\""
|
||||
wait "label=\"Bottom Sheet\"" 10000
|
||||
gesture pan 200 650 0 -300 500
|
||||
wait 1000
|
||||
gesture pan 200 400 0 300 500
|
||||
wait 1000
|
||||
press 200 424
|
||||
wait "id=\"agent-chat-scroll\"" 10000
|
||||
close
|
||||
@@ -28,12 +28,13 @@ bounds cannot establish measurement parity.
|
||||
compares them with the shipped headers. This catches missing C++ fields in the
|
||||
measurement path, which the Kotlin tests cannot exercise.
|
||||
|
||||
The package patch contains `InlineCodeFormattingTest`, which exercises actual
|
||||
Android spans in Robolectric native graphics mode, covering draw and measurement,
|
||||
span order, code inside paragraph/heading sizes, bold/italic composition, and
|
||||
links preserving code and emphasized prose fonts.
|
||||
It runs in the existing `test:android` CI job. To run only this regression locally,
|
||||
from `packages/app/android` after Expo prebuild:
|
||||
The vendored library (`packages/react-native-enriched-markdown`) contains
|
||||
`InlineCodeFormattingTest`, which exercises actual Android spans in Robolectric
|
||||
native graphics mode, covering draw and measurement, span order, code inside
|
||||
paragraph/heading sizes, bold/italic composition, and links preserving code and
|
||||
emphasized prose fonts. It runs in `npm run test:android`; CI does not run it.
|
||||
To run only this regression locally, from `packages/app/android` after Expo
|
||||
prebuild:
|
||||
|
||||
```sh
|
||||
./gradlew :react-native-enriched-markdown:testDebugUnitTest \
|
||||
|
||||
@@ -12,6 +12,43 @@ const DISABLE_DEFAULT_SEED_ONCE_KEY = "@paseo:e2e-disable-default-seed-once";
|
||||
const SEED_NONCE_KEY = "@paseo:e2e-seed-nonce";
|
||||
const REGISTRY_KEY = "@paseo:daemon-registry";
|
||||
|
||||
export async function openSidebarHostPicker(page: Page) {
|
||||
await page.getByRole("button", { name: "Hosts", exact: true }).click();
|
||||
}
|
||||
|
||||
export function sidebarHostSettingsButton(page: Page) {
|
||||
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
|
||||
}
|
||||
|
||||
export async function bindCommandCenterToEnter(page: Page) {
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
"@paseo:keyboard-shortcut-overrides",
|
||||
JSON.stringify({
|
||||
"command-center-toggle-cmd-k-mac": "Enter",
|
||||
"command-center-toggle-ctrl-k-non-mac": "Enter",
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectStandaloneSidebarHostSettingsButton(page: Page) {
|
||||
const gear = sidebarHostSettingsButton(page);
|
||||
await expect(gear).toBeVisible();
|
||||
expect(await gear.evaluate((button) => button.parentElement?.closest("button") === null)).toBe(
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
export async function activateSidebarHostSettingsWithKeyboard(page: Page) {
|
||||
const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
|
||||
await expect(host).toBeFocused();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(sidebarHostSettingsButton(page)).toBeFocused();
|
||||
await page.keyboard.press("Enter");
|
||||
}
|
||||
|
||||
interface SavedSettingsHostInput {
|
||||
serverId: string;
|
||||
label: string;
|
||||
|
||||
@@ -132,7 +132,7 @@ using namespace facebook::react;
|
||||
if (!props.maintainVisibleContentPosition || scrollView.contentSize.width > self.frame.size.width) {
|
||||
return nil;
|
||||
}
|
||||
NSArray<UIView *> *children = [self contentView].subviews;
|
||||
NSArray<UIView *> *children = [self paseoScrollContentView].subviews;
|
||||
NSUInteger first = props.maintainVisibleContentPosition.value().minIndexForVisible;
|
||||
for (NSUInteger index = first; index < children.count; ++index) {
|
||||
UIView *child = children[index];
|
||||
@@ -149,7 +149,11 @@ using namespace facebook::react;
|
||||
[((RCTViewComponentView *)view).nativeId isEqualToString:@"paseo-end-pin"];
|
||||
}
|
||||
|
||||
- (UIView *)contentView
|
||||
// Not `contentView`: that name would override RCTViewComponentView's getter, which
|
||||
// react-native-gesture-handler reads to pick the view a gesture binds to. Bound to the content
|
||||
// child, a bottom sheet's scroll gesture loses its pairing with the scroll view, so body drags
|
||||
// neither expand the sheet nor scroll the list until the sheet is at its top detent.
|
||||
- (UIView *)paseoScrollContentView
|
||||
{
|
||||
for (UIView *child in self.containerView.subviews) {
|
||||
if (![child conformsToProtocol:@protocol(RCTCustomPullToRefreshViewProtocol)]) {
|
||||
|
||||
@@ -19,6 +19,7 @@ android {
|
||||
|
||||
dependencies {
|
||||
implementation "androidx.customview:customview:1.1.0"
|
||||
implementation "com.facebook.react:react-android"
|
||||
testImplementation "junit:junit:4.13.2"
|
||||
androidTestImplementation "androidx.test:runner:1.6.2"
|
||||
androidTestImplementation "androidx.test.ext:junit:1.2.1"
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package sh.paseo.terminal
|
||||
|
||||
import android.text.InputType
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.facebook.react.bridge.BridgeReactContext
|
||||
import com.facebook.react.uimanager.DisplayMetricsHolder
|
||||
import com.facebook.react.uimanager.ThemedReactContext
|
||||
import com.facebook.react.views.textinput.ReactEditText
|
||||
import com.facebook.react.views.textinput.ReactTextInputManager
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
/**
|
||||
* Builds React Native's own text input and applies `nativeID` through its view manager, which is
|
||||
* how Fabric mounts the hidden terminal input. The app runs bridgeless, so the context is too.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class TerminalInputKeyboardTest {
|
||||
private val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
|
||||
@Test fun terminalInputAsksTheKeyboardNotToLearnWhatIsTyped() {
|
||||
onInput("paseo-terminal-input") { input, editorInfo ->
|
||||
assertNotEquals(
|
||||
"The keyboard must not learn passwords typed at a terminal prompt",
|
||||
0,
|
||||
editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING,
|
||||
)
|
||||
assertEquals(
|
||||
"Suggestions stay off and the input stays multiline",
|
||||
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or InputType.TYPE_TEXT_FLAG_MULTI_LINE,
|
||||
editorInfo.inputType and (InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or InputType.TYPE_TEXT_FLAG_MULTI_LINE),
|
||||
)
|
||||
val connection = checkNotNull(input.onCreateInputConnection(EditorInfo()))
|
||||
connection.setComposingText("su", 1)
|
||||
connection.commitText("sudo ls", 1)
|
||||
connection.deleteSurroundingText(1, 0)
|
||||
assertEquals("sudo l", input.text.toString())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun otherInputsKeepPersonalizedLearning() {
|
||||
onInput("message-composer") { _, editorInfo ->
|
||||
assertEquals(0, editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onInput(nativeId: String, check: (ReactEditText, EditorInfo) -> Unit) {
|
||||
TerminalInputKeyboard.install()
|
||||
instrumentation.runOnMainSync {
|
||||
val app = instrumentation.targetContext
|
||||
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(app)
|
||||
val react = object : BridgeReactContext(app) {
|
||||
override fun isBridgeless() = true
|
||||
}
|
||||
val input = ReactEditText(ThemedReactContext(react, app, null, -1))
|
||||
input.inputType = InputType.TYPE_CLASS_TEXT or
|
||||
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
|
||||
InputType.TYPE_TEXT_FLAG_MULTI_LINE
|
||||
ReactTextInputManager().setNativeId(input, nativeId)
|
||||
val editorInfo = EditorInfo()
|
||||
input.onCreateInputConnection(editorInfo)
|
||||
check(input, editorInfo)
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -7,6 +7,8 @@ class PaseoTerminalModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("PaseoTerminal")
|
||||
|
||||
OnCreate { TerminalInputKeyboard.install() }
|
||||
|
||||
View(PaseoTerminalView::class) {
|
||||
Events("onCellMetrics")
|
||||
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package sh.paseo.terminal
|
||||
|
||||
import android.view.View
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.TextView
|
||||
import com.facebook.react.bridge.UiThreadUtil
|
||||
import com.facebook.react.uimanager.util.ReactFindViewUtil
|
||||
|
||||
// Matched against the hidden terminal input's `nativeID`
|
||||
// (TERMINAL_INPUT_NATIVE_ID in terminal-input.native.tsx).
|
||||
private const val TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input"
|
||||
|
||||
/**
|
||||
* Keeps what is typed at a terminal prompt, such as a `sudo` password, out of the keyboard's
|
||||
* learned words. React Native's TextInput has no prop for IME_FLAG_NO_PERSONALIZED_LEARNING, so the
|
||||
* flag is added when the input receives its `nativeID`, before it can take focus.
|
||||
*
|
||||
* React Native replaces `imeOptions` when `returnKeyType` or `disableFullscreenUI` is set, so the
|
||||
* terminal input sets neither.
|
||||
*/
|
||||
internal object TerminalInputKeyboard : ReactFindViewUtil.OnMultipleViewsFoundListener {
|
||||
fun install() {
|
||||
UiThreadUtil.runOnUiThread {
|
||||
ReactFindViewUtil.addViewsListener(this, setOf(TERMINAL_INPUT_NATIVE_ID))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onViewFound(view: View, nativeId: String) {
|
||||
val input = view as? TextView ?: return
|
||||
input.imeOptions = input.imeOptions or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/app",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"private": true,
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
@@ -40,7 +40,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
@@ -125,7 +125,7 @@
|
||||
"react-native": "0.86.3",
|
||||
"react-native-draggable-flatlist": "^4.0.3",
|
||||
"react-native-edge-to-edge": "^1.7.0",
|
||||
"react-native-enriched-markdown": "1.2.0-nightly-20261014-766fc0e67",
|
||||
"react-native-enriched-markdown": "*",
|
||||
"react-native-gesture-handler": "~2.32.0",
|
||||
"react-native-keyboard-controller": "1.21.12",
|
||||
"react-native-nitro-modules": "0.35.5",
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { createAssistantSelectionClipboardContent } from "./content.web";
|
||||
import { createElement as h } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { within } from "@testing-library/dom";
|
||||
import { EnrichedMarkdownText } from "react-native-enriched-markdown";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { WEB_RENDERERS } from "@/components/markdown/renderers.web";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
createAssistantSelectionClipboardContent,
|
||||
createElementClipboardContent,
|
||||
} from "./content.web";
|
||||
import { MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE } from "./markup";
|
||||
|
||||
const fixture = `
|
||||
<div data-testid="assistant-message">
|
||||
@@ -953,3 +968,158 @@ it("copies a workspace image path instead of its temporary display URL", () => {
|
||||
"",
|
||||
);
|
||||
});
|
||||
|
||||
describe("quote copy", () => {
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement | undefined;
|
||||
const toast: ToastApi = { show: () => () => {}, copied: () => {}, error: () => {} };
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
afterEach(() => {
|
||||
const mounted = root;
|
||||
if (mounted) flushSync(() => mounted.unmount());
|
||||
root = undefined;
|
||||
host?.remove();
|
||||
host = undefined;
|
||||
});
|
||||
|
||||
/** Renders Markdown through the web engine with the app's renderers, as a message does. */
|
||||
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
|
||||
if (!host || !root) {
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
}
|
||||
const mounted = root;
|
||||
flushSync(() =>
|
||||
mounted.render(
|
||||
h(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
h(
|
||||
I18nextProvider,
|
||||
{ i18n },
|
||||
h(ToastApiProvider, {
|
||||
api: toast,
|
||||
children: h(EnrichedMarkdownText, {
|
||||
markdown,
|
||||
flavor: "github",
|
||||
md4cFlags: { latexMath: false, admonitions: true },
|
||||
renderers: WEB_RENDERERS,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rendered = host;
|
||||
await vi.waitFor(() => expect(rendered.textContent).toContain(lastText));
|
||||
return rendered;
|
||||
}
|
||||
|
||||
it("copies a quote's body with its formatting and without the quote marker", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Hello **team**, see [the PR](https://example.test/pr).\n>\n> - Review\n>\n> > Nested reply",
|
||||
"Nested reply",
|
||||
);
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe(
|
||||
"Hello **team**, see [the PR](https://example.test/pr).\n\n- Review\n\n> Nested reply",
|
||||
);
|
||||
expect(content?.html).toContain("<strong>team</strong>");
|
||||
expect(content?.html).toContain("<blockquote>");
|
||||
expect(content?.html).not.toContain("Copy quote");
|
||||
});
|
||||
|
||||
it("gives a nested quote its own control that copies only the nested quote", async () => {
|
||||
const rendered = await renderMarkdown("> Outer\n>\n> > Nested reply", "Nested reply");
|
||||
const nested = fixtureElement(rendered, "blockquote", 1);
|
||||
|
||||
expect(within(rendered).getAllByRole("button", { name: "Copy quote" })).toHaveLength(2);
|
||||
expect(within(nested).getAllByRole("button", { name: "Copy quote" })).toHaveLength(1);
|
||||
expect(createElementClipboardContent(nested)?.plainText).toBe("Nested reply");
|
||||
});
|
||||
|
||||
it("copies a code block inside a quote as its fence and keeps the code's own control", async () => {
|
||||
const rendered = await renderMarkdown("> Run:\n>\n> ```sh\n> npm test\n> ```", "npm test");
|
||||
const quote = fixtureElement(rendered, "blockquote");
|
||||
|
||||
expect(within(quote).getByRole("button", { name: "Copy code" })).toBeTruthy();
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe("Run:\n\n```sh\nnpm test\n```");
|
||||
});
|
||||
|
||||
it("copies what a streaming quote shows at the time of the copy", async () => {
|
||||
const first = await renderMarkdown("> First draft", "First draft");
|
||||
const quote = fixtureElement(first, "blockquote");
|
||||
|
||||
const revised = await renderMarkdown("> First draft, revised", "revised");
|
||||
|
||||
expect(fixtureElement(revised, "blockquote")).toBe(quote);
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe("First draft, revised");
|
||||
});
|
||||
|
||||
it("copies literal Markdown characters raw in text/plain and escaped in text/html", async () => {
|
||||
const rendered = await renderMarkdown("> literal \\_word\\_ stays literal", "stays literal");
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe("literal _word_ stays literal");
|
||||
expect(content?.html).toContain("literal _word_ stays literal");
|
||||
expect(content?.html).not.toContain("<em>");
|
||||
});
|
||||
|
||||
it("gives an admonition no copy control", async () => {
|
||||
const rendered = await renderMarkdown("> [!NOTE]\n> Heads up", "Heads up");
|
||||
|
||||
expect(within(rendered).queryByRole("button", { name: "Copy quote" })).toBeNull();
|
||||
});
|
||||
|
||||
it("copies a nested admonition as its callout source", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
|
||||
"After",
|
||||
);
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe("Before\n\n> [!WARNING]\n> Do not deploy.\n\nAfter");
|
||||
});
|
||||
|
||||
it("copies a selection across an admonition as the text it shows, without a callout marker", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
|
||||
"After",
|
||||
);
|
||||
rendered.setAttribute("data-testid", "assistant-message");
|
||||
const body = tokenText(rendered, "Do not deploy.");
|
||||
|
||||
expect(
|
||||
copyBetween([body, "Do not ".length], [tokenText(rendered, "After"), 5])?.plainText,
|
||||
).toBe("deploy.\n\nAfter");
|
||||
expect(
|
||||
copyBetween([tokenText(rendered, "Before"), 0], [tokenText(rendered, "Warning"), 4])
|
||||
?.plainText,
|
||||
).toBe("Before\n\nWarn");
|
||||
expect(
|
||||
copyBetween([tokenText(rendered, "Before"), 0], [body, "Do not".length])?.plainText,
|
||||
).not.toContain("[!WARNING]");
|
||||
});
|
||||
|
||||
it("copies a rendered Mermaid diagram as its fence", () => {
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.innerHTML = `<p>Before</p><div ${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}="graph TD; A-->B" data-paseo-markdown-language="mermaid"><svg aria-label="diagram"></svg></div><p>After</p>`;
|
||||
|
||||
expect(createElementClipboardContent(quote)?.plainText).toBe(
|
||||
"Before\n\n```mermaid\ngraph TD; A-->B\n```\n\nAfter",
|
||||
);
|
||||
});
|
||||
|
||||
it("copies nothing from a quote that holds only its control", () => {
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.innerHTML = '<button data-paseo-markdown-ignore="true">Copy quote</button>';
|
||||
|
||||
expect(createElementClipboardContent(quote)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,9 +6,12 @@ import {
|
||||
type MarkdownClipboardContent,
|
||||
} from "@/utils/rich-clipboard";
|
||||
import {
|
||||
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
|
||||
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
|
||||
MARKDOWN_COPY_ALIGN_ATTRIBUTE,
|
||||
MARKDOWN_COPY_ALT_ATTRIBUTE,
|
||||
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_IGNORE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE,
|
||||
@@ -91,6 +94,17 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
} else {
|
||||
turndown.escape = (text) => text;
|
||||
}
|
||||
// An admonition copies as its `> [!TYPE]` source.
|
||||
turndown.addRule("admonition", {
|
||||
filter: (node) => node.hasAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE),
|
||||
replacement: (content, node) => {
|
||||
const type = (node as Element)
|
||||
.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE)!
|
||||
.toUpperCase();
|
||||
const body = content.replace(/^\n+|\n+$/g, "");
|
||||
return `\n\n${`[!${type}]\n${body}`.replace(/^/gm, "> ")}\n\n`;
|
||||
},
|
||||
});
|
||||
turndown.addRule("gfmStrikethrough", {
|
||||
filter: ["del", "s"],
|
||||
replacement: (content) => `~~${content}~~`,
|
||||
@@ -120,6 +134,53 @@ function isWebUrl(href: string): boolean {
|
||||
const markdownTurndown = createTurndown("markdown");
|
||||
const plainTurndown = createTurndown("plain");
|
||||
|
||||
/**
|
||||
* A fence rendered as something other than its code, such as a Mermaid diagram, carries
|
||||
* its source in an attribute. Put the code block back so the fence is what gets copied.
|
||||
*/
|
||||
function restoreFenceSources(container: Element): void {
|
||||
for (const region of container.querySelectorAll(`[${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}]`)) {
|
||||
const source = region.getAttribute(MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE);
|
||||
if (source === null) continue;
|
||||
const pre = document.createElement("pre");
|
||||
const code = document.createElement("code");
|
||||
const language = region.getAttribute(MARKDOWN_COPY_LANGUAGE_ATTRIBUTE);
|
||||
if (language) code.className = `language-${language}`;
|
||||
code.textContent = source;
|
||||
pre.append(code);
|
||||
region.replaceWith(pre);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clipboard payload for everything inside `element`, without the element's own syntax:
|
||||
* a quote's body carries no `>` prefix. Null when there is nothing to copy.
|
||||
*/
|
||||
export function createElementClipboardContent(element: Element): MarkdownClipboardContent | null {
|
||||
const container = document.createElement("div");
|
||||
container.append(...Array.from(element.childNodes, (child) => child.cloneNode(true)));
|
||||
const originals = element.querySelectorAll("*");
|
||||
const copies = container.querySelectorAll("*");
|
||||
originals.forEach((original, index) => copySemanticAttributes(original, copies[index]!));
|
||||
restoreFenceSources(container);
|
||||
restoreAdmonitions(container);
|
||||
restoreMarkdownElements(container);
|
||||
return clipboardContentFromMarkup(container);
|
||||
}
|
||||
|
||||
function clipboardContentFromMarkup(container: HTMLElement): MarkdownClipboardContent | null {
|
||||
const markdown = markdownTurndown.turndown(container).trim();
|
||||
if (!markdown) {
|
||||
return null;
|
||||
}
|
||||
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
|
||||
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
|
||||
// literal in a rich target.
|
||||
const plainText = plainTurndown.turndown(container).trim();
|
||||
const content = createSelectionClipboardContent(markdown, plainText);
|
||||
return { ...content, html: flattenClipboardListMarkup(content.html) };
|
||||
}
|
||||
|
||||
export function createAssistantSelectionClipboardContent(
|
||||
selection: Selection | null,
|
||||
): MarkdownClipboardContent | null {
|
||||
@@ -145,17 +206,7 @@ export function createAssistantSelectionClipboardContent(
|
||||
container.append(cloneMarkdownSelection(part.range, part.message));
|
||||
}
|
||||
restoreMarkdownElements(container);
|
||||
|
||||
const markdown = markdownTurndown.turndown(container).trim();
|
||||
if (!markdown) {
|
||||
return null;
|
||||
}
|
||||
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
|
||||
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
|
||||
// literal in a rich target.
|
||||
const plainText = plainTurndown.turndown(container).trim();
|
||||
const content = createSelectionClipboardContent(markdown, plainText);
|
||||
return { ...content, html: flattenClipboardListMarkup(content.html) };
|
||||
return clipboardContentFromMarkup(container);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -702,6 +753,28 @@ function numberOrderedListItems(list: Element, start: number): void {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The library renders an admonition as a box with a generated title. Keep it a quote
|
||||
* with its type, so it copies as its callout source rather than as the title's prose.
|
||||
* Only a whole-element copy does this: a selection cannot tell from its cloned markup
|
||||
* whether it holds the whole callout, so it copies the text it shows.
|
||||
*/
|
||||
function restoreAdmonitions(container: Element): void {
|
||||
const admonitions = Array.from(
|
||||
container.querySelectorAll(`[${MARKDOWN_ADMONITION_TYPE_ATTRIBUTE}]`),
|
||||
);
|
||||
for (const admonition of admonitions.toReversed()) {
|
||||
admonition.querySelector(`:scope > [${MARKDOWN_ADMONITION_TITLE_ATTRIBUTE}]`)?.remove();
|
||||
const quote = document.createElement("blockquote");
|
||||
quote.setAttribute(
|
||||
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
|
||||
admonition.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE) ?? "note",
|
||||
);
|
||||
quote.append(...admonition.childNodes);
|
||||
admonition.replaceWith(quote);
|
||||
}
|
||||
}
|
||||
|
||||
function unwrapIncompleteTables(container: HTMLElement): void {
|
||||
for (const table of container.querySelectorAll("table")) {
|
||||
if (hasUsableTableColumnContract(table)) {
|
||||
|
||||
@@ -6,9 +6,13 @@ export const MARKDOWN_COPY_UNWRAP_ATTRIBUTE = "data-paseo-markdown-unwrap";
|
||||
export const MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE = "data-paseo-markdown-recognized-link";
|
||||
export const MARKDOWN_COPY_LIST_START_ATTRIBUTE = "data-paseo-markdown-list-start";
|
||||
export const MARKDOWN_COPY_LANGUAGE_ATTRIBUTE = "data-paseo-markdown-language";
|
||||
export const MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE = "data-paseo-markdown-fence-source";
|
||||
export const MARKDOWN_COPY_ALIGN_ATTRIBUTE = "data-paseo-markdown-align";
|
||||
export const MARKDOWN_COPY_SRC_ATTRIBUTE = "data-paseo-markdown-src";
|
||||
export const MARKDOWN_COPY_ALT_ATTRIBUTE = "data-paseo-markdown-alt";
|
||||
/** Set by the Markdown library's web admonition renderer on the box and on its generated title. */
|
||||
export const MARKDOWN_ADMONITION_TYPE_ATTRIBUTE = "data-enrm-admonition-type";
|
||||
export const MARKDOWN_ADMONITION_TITLE_ATTRIBUTE = "data-enrm-admonition-title";
|
||||
|
||||
/**
|
||||
* Trailing line breaks, with any indentation that followed the last one.
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
View,
|
||||
Text,
|
||||
type StyleProp,
|
||||
type TextStyle,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import React, { useCallback, useMemo, useState } from "react";
|
||||
import { View, Text, type StyleProp, type TextStyle, type ViewStyle } from "react-native";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import { Check, Copy } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { HighlightToken } from "@getpaseo/highlight";
|
||||
import { BlockCopyButton } from "@/components/markdown/block-copy-button";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { syntaxTokenStyleFor } from "@/styles/syntax-token-styles";
|
||||
@@ -85,6 +77,7 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
[renderedCode, language],
|
||||
);
|
||||
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
|
||||
@@ -93,7 +86,11 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
// Copy the code without its trailing blank lines. A fence body ends in a newline,
|
||||
// and ends in more than one when the author left a blank line before the closing
|
||||
// fence; pasting any of them into a terminal runs the last line.
|
||||
const getCode = useCallback(() => code.replace(TRAILING_CODE_LINE_BREAKS, ""), [code]);
|
||||
const copyCode = useCallback(async () => {
|
||||
const content = code.replace(TRAILING_CODE_LINE_BREAKS, "");
|
||||
if (!content) return false;
|
||||
return Clipboard.setStringAsync(content);
|
||||
}, [code]);
|
||||
|
||||
return (
|
||||
<View
|
||||
@@ -111,7 +108,11 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
|
||||
{renderedCode}
|
||||
</Text>
|
||||
)}
|
||||
<CopyButton getCode={getCode} visible={controlsVisible} />
|
||||
<BlockCopyButton
|
||||
onCopy={copyCode}
|
||||
visible={controlsVisible}
|
||||
label={t("message.actions.copyCode")}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
@@ -168,87 +169,3 @@ function splitFenceStyle(inheritedStyles: TextStyle, textStyle: TextStyle): Spli
|
||||
innerTextStyle: [inheritedStyles, textOnly],
|
||||
};
|
||||
}
|
||||
|
||||
interface CopyButtonProps {
|
||||
getCode: () => string;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
const CopyButton = React.memo(function CopyButton({ getCode, visible }: CopyButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handlePress = useCallback(async () => {
|
||||
const content = getCode();
|
||||
if (!content) return;
|
||||
await Clipboard.setStringAsync(content);
|
||||
setCopied(true);
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
resetRef.current = setTimeout(() => {
|
||||
setCopied(false);
|
||||
resetRef.current = null;
|
||||
}, COPIED_RESET_MS);
|
||||
}, [getCode]);
|
||||
|
||||
const visibilityStyle = visible
|
||||
? copyButtonStyles.containerVisible
|
||||
: copyButtonStyles.containerHidden;
|
||||
const wrapperStyle = useMemo(
|
||||
() => [copyButtonStyles.container, visibilityStyle],
|
||||
[visibilityStyle],
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
onPress={handlePress}
|
||||
style={wrapperStyle}
|
||||
pointerEvents={visible ? "auto" : "none"}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={copied ? t("message.actions.copied") : t("message.actions.copyCode")}
|
||||
hitSlop={8}
|
||||
dataSet={markdownCopyDataSet.ignore}
|
||||
>
|
||||
{({ hovered }) => {
|
||||
const iconColor = hovered
|
||||
? copyButtonStyles.iconHoveredColor.color
|
||||
: copyButtonStyles.iconColor.color;
|
||||
return copied ? (
|
||||
<Check size={14} color={iconColor} />
|
||||
) : (
|
||||
<Copy size={14} color={iconColor} />
|
||||
);
|
||||
}}
|
||||
</Pressable>
|
||||
);
|
||||
});
|
||||
|
||||
const copyButtonStyles = StyleSheet.create((theme) => ({
|
||||
container: {
|
||||
position: "absolute",
|
||||
top: theme.spacing[2],
|
||||
right: theme.spacing[2],
|
||||
padding: theme.spacing[1],
|
||||
},
|
||||
containerVisible: {
|
||||
opacity: 1,
|
||||
},
|
||||
containerHidden: {
|
||||
opacity: 0,
|
||||
},
|
||||
iconColor: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
iconHoveredColor: {
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
import type { GestureResponderEvent } from "react-native";
|
||||
import { Plus, Server, Settings } from "lucide-react-native";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { HostStatusDot } from "@/components/host-status-dot";
|
||||
@@ -80,19 +79,15 @@ export function HostPickerOption({
|
||||
? formatActiveConnectionLabel(activeConnection)
|
||||
: undefined;
|
||||
const leadingSlot = useMemo(() => <HostStatusDotSlot serverId={serverId} />, [serverId]);
|
||||
const handleSettingsPress = useCallback(
|
||||
(event: GestureResponderEvent) => {
|
||||
event.stopPropagation();
|
||||
onOpenHostSettings?.(serverId);
|
||||
},
|
||||
[onOpenHostSettings, serverId],
|
||||
);
|
||||
const trailingSlot = useMemo(() => {
|
||||
const handleSettingsPress = useCallback(() => {
|
||||
onOpenHostSettings?.(serverId);
|
||||
}, [onOpenHostSettings, serverId]);
|
||||
const trailingAction = useMemo(() => {
|
||||
if (!onOpenHostSettings) return undefined;
|
||||
return (
|
||||
<Pressable
|
||||
onPress={handleSettingsPress}
|
||||
hitSlop={8}
|
||||
style={styles.settingsAction}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Open ${label} settings`}
|
||||
>
|
||||
@@ -112,7 +107,7 @@ export function HostPickerOption({
|
||||
label={label}
|
||||
description={connectionLabel}
|
||||
leadingSlot={leadingSlot}
|
||||
trailingSlot={trailingSlot}
|
||||
trailingAction={trailingAction}
|
||||
selected={selected}
|
||||
active={active}
|
||||
onPress={onPress}
|
||||
@@ -319,6 +314,12 @@ export function HostPicker({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
settingsAction: {
|
||||
flex: 1,
|
||||
justifyContent: "center",
|
||||
paddingLeft: theme.spacing[1],
|
||||
paddingRight: theme.spacing[3],
|
||||
},
|
||||
statusDotSlot: {
|
||||
width: theme.iconSize.sm,
|
||||
height: theme.iconSize.sm,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { within } from "@testing-library/dom";
|
||||
import { userEvent } from "vitest/browser";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import type { ToastApi } from "@/components/toast-host";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { BlockCopyButton } from "./block-copy-button";
|
||||
|
||||
const LABEL = "Copy quote";
|
||||
|
||||
let errors: string[] = [];
|
||||
const toast: ToastApi = {
|
||||
show: () => () => {},
|
||||
copied: () => {},
|
||||
error: (message) => errors.push(message),
|
||||
};
|
||||
|
||||
describe("BlockCopyButton", () => {
|
||||
let root: Root;
|
||||
let host: HTMLDivElement;
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage("en");
|
||||
errors = [];
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
host.remove();
|
||||
});
|
||||
|
||||
function render(onCopy: () => Promise<boolean>, visible = true) {
|
||||
flushSync(() =>
|
||||
root.render(
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ToastApiProvider api={toast}>
|
||||
<BlockCopyButton onCopy={onCopy} visible={visible} label={LABEL} />
|
||||
</ToastApiProvider>
|
||||
</I18nextProvider>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function button(name = LABEL): HTMLElement {
|
||||
return within(host).getByRole("button", { name });
|
||||
}
|
||||
|
||||
it("shows Copied after a write and returns to its label", async () => {
|
||||
let calls = 0;
|
||||
render(async () => {
|
||||
calls += 1;
|
||||
return true;
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
await vi.waitFor(() => expect(button()).toBeTruthy(), { timeout: 2500 });
|
||||
expect(calls).toBe(1);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["resolves false", async () => false],
|
||||
[
|
||||
"rejects",
|
||||
async (): Promise<boolean> => {
|
||||
throw new Error("Clipboard denied");
|
||||
},
|
||||
],
|
||||
])("tells the user and never shows Copied when the write %s", async (_case, failure) => {
|
||||
let calls = 0;
|
||||
render(() => {
|
||||
calls += 1;
|
||||
return calls === 1 ? failure() : Promise.resolve(true);
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(errors).toEqual(["Unable to copy"]));
|
||||
expect(within(host).queryByRole("button", { name: "Copied" })).toBeNull();
|
||||
|
||||
await userEvent.click(button());
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
expect(calls).toBe(2);
|
||||
});
|
||||
|
||||
it("does not write twice while a write is pending", async () => {
|
||||
let finish!: (written: boolean) => void;
|
||||
let calls = 0;
|
||||
render(() => {
|
||||
calls += 1;
|
||||
return new Promise<boolean>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
});
|
||||
|
||||
await userEvent.click(button());
|
||||
await userEvent.click(button());
|
||||
expect(calls).toBe(1);
|
||||
|
||||
finish(true);
|
||||
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it("stays hidden until its block reveals it or it takes keyboard focus", async () => {
|
||||
render(async () => true, false);
|
||||
expect(getComputedStyle(button()).opacity).toBe("0");
|
||||
|
||||
await userEvent.tab();
|
||||
expect(document.activeElement).toBe(button());
|
||||
await vi.waitFor(() => expect(getComputedStyle(button()).opacity).toBe("1"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { memo, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { View } from "react-native";
|
||||
import { Check, Copy } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { markdownCopyDataSet } from "@/assistant-selection-copy/markup";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
|
||||
import { paneContentToolbarIconSize, ToolbarButton } from "@/components/ui/pane-content-toolbar";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useToast } from "@/contexts/toast-api-context";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
const ThemedCopy = withUnistyles(Copy, mutedIconColorMapping);
|
||||
const ThemedCheck = withUnistyles(Check, mutedIconColorMapping);
|
||||
|
||||
const COPIED_RESET_MS = 1500;
|
||||
|
||||
/** How far the copy glyph sits from the top and trailing edges of its block. */
|
||||
export function blockCopyGlyphInset(theme: Theme): number {
|
||||
return theme.spacing[2] + theme.spacing[1];
|
||||
}
|
||||
|
||||
interface BlockCopyButtonProps {
|
||||
/** Writes the block to the clipboard. Resolves false, or rejects, when nothing was written. */
|
||||
onCopy: () => Promise<boolean>;
|
||||
/** The block's own reveal state. Keyboard focus shows the button regardless. */
|
||||
visible: boolean;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The copy control in the top trailing corner of a Markdown block. The block is its
|
||||
* positioned ancestor.
|
||||
*/
|
||||
export const BlockCopyButton = memo(function BlockCopyButton({
|
||||
onCopy,
|
||||
visible,
|
||||
label,
|
||||
}: BlockCopyButtonProps) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const compact = useIsCompactFormFactor();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const writing = useRef(false);
|
||||
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const focus = useCallback(() => setFocused(true), []);
|
||||
const blur = useCallback(() => setFocused(false), []);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handlePress = useCallback(async () => {
|
||||
// A slow clipboard must not queue a second write behind the first.
|
||||
if (writing.current) return;
|
||||
writing.current = true;
|
||||
const written = await onCopy()
|
||||
.catch(() => false)
|
||||
.finally(() => {
|
||||
writing.current = false;
|
||||
});
|
||||
if (!written) {
|
||||
toast.error(t("common.errors.unableToCopy"));
|
||||
return;
|
||||
}
|
||||
setCopied(true);
|
||||
if (resetRef.current) clearTimeout(resetRef.current);
|
||||
resetRef.current = setTimeout(() => setCopied(false), COPIED_RESET_MS);
|
||||
}, [onCopy, t, toast]);
|
||||
|
||||
const shown = visible || focused;
|
||||
const Glyph = copied ? ThemedCheck : ThemedCopy;
|
||||
return (
|
||||
<View style={styles.corner(compact)} dataSet={markdownCopyDataSet.ignore}>
|
||||
<ToolbarButton
|
||||
compact={compact}
|
||||
label={copied ? t("message.actions.copied") : label}
|
||||
onPress={handlePress}
|
||||
onFocus={focus}
|
||||
onBlur={blur}
|
||||
style={shown ? styles.shown : styles.hidden}
|
||||
>
|
||||
<Glyph size={paneContentToolbarIconSize(compact)} />
|
||||
</ToolbarButton>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
// The glyph, not the button frame, sits on the inset; the frame overhangs it.
|
||||
corner: (compact: boolean) => {
|
||||
const frameOverhang =
|
||||
(smallIconButtonChromeFrameSize(compact) - paneContentToolbarIconSize(compact)) / 2;
|
||||
const inset = blockCopyGlyphInset(theme) - frameOverhang;
|
||||
return {
|
||||
position: "absolute" as const,
|
||||
top: inset,
|
||||
right: inset,
|
||||
pointerEvents: "box-none" as const,
|
||||
};
|
||||
},
|
||||
shown: { opacity: 1, pointerEvents: "auto" },
|
||||
hidden: { opacity: 0, pointerEvents: "none" },
|
||||
}));
|
||||
@@ -5,6 +5,10 @@ import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
|
||||
import { ZoomableViewport } from "@/components/zoomable-viewport";
|
||||
import {
|
||||
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
|
||||
} from "@/assistant-selection-copy/markup";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { MarkdownFenceRendererProps } from "./types";
|
||||
import { MermaidFullscreenViewer } from "./fullscreen-viewer.web";
|
||||
@@ -81,6 +85,16 @@ function MermaidFenceHostImpl({
|
||||
[visible],
|
||||
);
|
||||
const sourceVisible = !diagramVisible;
|
||||
// A visible diagram stands in for its fence, so copying the surrounding block takes
|
||||
// the source from here: the revision on screen, which lags `code` while a streamed
|
||||
// revision renders. The source view copies as its own code block.
|
||||
const diagramCopyAttributes =
|
||||
diagramVisible && visible
|
||||
? {
|
||||
[MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE]: visible.source,
|
||||
[MARKDOWN_COPY_LANGUAGE_ATTRIBUTE]: "mermaid",
|
||||
}
|
||||
: null;
|
||||
const viewportStyle = diagramVisible ? diagramStyle : measuringStyle;
|
||||
|
||||
return (
|
||||
@@ -111,7 +125,7 @@ function MermaidFenceHostImpl({
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
<div inert={!diagramVisible} style={boundaryStyle}>
|
||||
<div inert={!diagramVisible} style={boundaryStyle} {...diagramCopyAttributes}>
|
||||
<ZoomableViewport
|
||||
accessibilityLabel={t("message.diagram.diagram")}
|
||||
actions={actions}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import type { BlockquoteRendererProps } from "react-native-enriched-markdown";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { createElementClipboardContent } from "@/assistant-selection-copy/content.web";
|
||||
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
|
||||
import { paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { writeClipboardContent } from "@/utils/rich-clipboard";
|
||||
import { getDefaultMarkdownClipboardEnvironment } from "@/utils/rich-clipboard-default-environment";
|
||||
import { BlockCopyButton, blockCopyGlyphInset } from "./block-copy-button";
|
||||
|
||||
interface WebBlockquoteProps extends BlockquoteRendererProps {
|
||||
copyGlyphInset: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Room the quote reserves so the control never covers its text. Compact layouts always
|
||||
* show the control, so it gets a band above the body and the text keeps the full width.
|
||||
* Wide layouts reveal it on hover, where a band would leave an empty strip above every
|
||||
* quote, so the text wraps short of it instead.
|
||||
*/
|
||||
function copyRoom(compact: boolean, glyphInset: number) {
|
||||
if (compact) {
|
||||
return { paddingTop: glyphInset + paneContentToolbarIconSize(compact) + glyphInset };
|
||||
}
|
||||
return { paddingRight: smallIconButtonChromeFrameSize(compact) + glyphInset };
|
||||
}
|
||||
|
||||
/** A quote with a control that copies its body, for drafts an agent wrote to be pasted elsewhere. */
|
||||
export const WebBlockquote = withUnistyles(
|
||||
function WebBlockquote({ blockquoteProps, children, copyGlyphInset }: WebBlockquoteProps) {
|
||||
const { t } = useTranslation();
|
||||
const quote = useRef<HTMLQuoteElement>(null);
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const compact = useIsCompactFormFactor();
|
||||
const enter = useCallback(() => setHovered(true), []);
|
||||
const leave = useCallback(() => setHovered(false), []);
|
||||
const style = useMemo(
|
||||
() => ({
|
||||
...blockquoteProps.style,
|
||||
position: "relative" as const,
|
||||
...copyRoom(compact, copyGlyphInset),
|
||||
}),
|
||||
[blockquoteProps.style, compact, copyGlyphInset],
|
||||
);
|
||||
const copy = useCallback(async () => {
|
||||
// Read the rendered body at press time: a streaming quote copies what it shows now.
|
||||
const content = quote.current && createElementClipboardContent(quote.current);
|
||||
if (!content) return false;
|
||||
return writeClipboardContent(content, getDefaultMarkdownClipboardEnvironment());
|
||||
}, []);
|
||||
return (
|
||||
<blockquote
|
||||
{...blockquoteProps}
|
||||
ref={quote}
|
||||
style={style}
|
||||
onPointerEnter={enter}
|
||||
onPointerLeave={leave}
|
||||
>
|
||||
<BlockCopyButton
|
||||
onCopy={copy}
|
||||
visible={hovered || compact}
|
||||
label={t("message.actions.copyQuote")}
|
||||
/>
|
||||
{children}
|
||||
</blockquote>
|
||||
);
|
||||
},
|
||||
(theme) => ({ copyGlyphInset: blockCopyGlyphInset(theme) }),
|
||||
);
|
||||
@@ -14,6 +14,7 @@ import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { MermaidFence } from "./fence/mermaid";
|
||||
import { isRecognizedLink, markdownLinkSource } from "./source";
|
||||
import { WebBlockquote } from "./quote-block.web";
|
||||
|
||||
const ThemedCodeBlock = withUnistyles(HighlightedCodeBlock);
|
||||
const codeStyle = (theme: Theme) => ({
|
||||
@@ -111,4 +112,8 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
export const WEB_RENDERERS: MarkdownRenderers = { codeBlock: WebCodeBlock, link: WebLink };
|
||||
export const WEB_RENDERERS: MarkdownRenderers = {
|
||||
codeBlock: WebCodeBlock,
|
||||
link: WebLink,
|
||||
blockquote: WebBlockquote,
|
||||
};
|
||||
|
||||
@@ -72,6 +72,7 @@ import { buildDesktopFrameStyle } from "./combobox-frame-style";
|
||||
export { buildDesktopFrameStyle } from "./combobox-frame-style";
|
||||
|
||||
const IS_WEB = isWeb;
|
||||
const TRAILING_ACTION_DATASET = { comboboxTrailingAction: true };
|
||||
|
||||
export type ComboboxOption = ComboboxOptionModel;
|
||||
export type ComboboxDesktopPlacement = "top-start" | "bottom-start";
|
||||
@@ -235,6 +236,11 @@ export interface ComboboxItemProps {
|
||||
kind?: "directory" | "file";
|
||||
leadingSlot?: ReactNode;
|
||||
trailingSlot?: ReactNode;
|
||||
/**
|
||||
* A button shown outside the row's own pressable. The button owns its spacing
|
||||
* and hit area.
|
||||
*/
|
||||
trailingAction?: ReactNode;
|
||||
selected?: boolean;
|
||||
active?: boolean;
|
||||
disabled?: boolean;
|
||||
@@ -252,6 +258,7 @@ export function ComboboxItem({
|
||||
kind,
|
||||
leadingSlot,
|
||||
trailingSlot,
|
||||
trailingAction,
|
||||
selected,
|
||||
active,
|
||||
disabled,
|
||||
@@ -300,15 +307,29 @@ export function ComboboxItem({
|
||||
[labelPrefix],
|
||||
);
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
testID={testID}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={itemPressableStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel ?? label}
|
||||
>
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const handleHoverIn = useCallback(() => setHovered(true), []);
|
||||
const handleHoverOut = useCallback(() => setHovered(false), []);
|
||||
const splitPressableStyle = useCallback(
|
||||
({ pressed }: PressableStateCallbackType) => [
|
||||
styles.comboboxItemSplitPressable,
|
||||
pressed && (elevated ? styles.comboboxItemPressedElevated : styles.comboboxItemPressed),
|
||||
],
|
||||
[elevated],
|
||||
);
|
||||
const splitRowStyle = useMemo(
|
||||
() => [
|
||||
styles.comboboxItem,
|
||||
styles.comboboxItemSplitRow,
|
||||
hovered && (elevated ? styles.comboboxItemHoveredElevated : styles.comboboxItemHovered),
|
||||
active && styles.comboboxItemActive,
|
||||
disabled && styles.comboboxItemDisabled,
|
||||
],
|
||||
[active, disabled, elevated, hovered],
|
||||
);
|
||||
|
||||
const content = (
|
||||
<>
|
||||
{leadingContent}
|
||||
<View style={itemContentStyle}>
|
||||
{labelPrefix ? (
|
||||
@@ -333,7 +354,40 @@ export function ComboboxItem({
|
||||
{trailingSlot}
|
||||
</View>
|
||||
) : null}
|
||||
</Pressable>
|
||||
</>
|
||||
);
|
||||
|
||||
if (!trailingAction) {
|
||||
return (
|
||||
<Pressable
|
||||
testID={testID}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={itemPressableStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel ?? label}
|
||||
>
|
||||
{content}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={splitRowStyle} onPointerEnter={handleHoverIn} onPointerLeave={handleHoverOut}>
|
||||
<Pressable
|
||||
testID={testID}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={splitPressableStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel ?? label}
|
||||
>
|
||||
{content}
|
||||
</Pressable>
|
||||
<View style={styles.comboboxItemActionSlot} dataSet={TRAILING_ACTION_DATASET}>
|
||||
{trailingAction}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -898,6 +952,10 @@ function dispatchDesktopKey(
|
||||
return true;
|
||||
}
|
||||
if (key === "Enter") {
|
||||
// Consume the shortcut but keep the browser's default button activation.
|
||||
if (isWeb && document.activeElement?.matches("[data-combobox-trailing-action] button")) {
|
||||
return true;
|
||||
}
|
||||
if (input.orderedVisibleOptions.length === 0) return false;
|
||||
event?.preventDefault();
|
||||
handleDesktopEnterKey(input);
|
||||
@@ -1742,6 +1800,26 @@ const styles = StyleSheet.create((theme) => ({
|
||||
marginBottom: theme.spacing[1],
|
||||
}),
|
||||
},
|
||||
// Share the highlight while each control owns its padding and hit area.
|
||||
comboboxItemSplitRow: {
|
||||
gap: 0,
|
||||
paddingHorizontal: 0,
|
||||
paddingVertical: 0,
|
||||
},
|
||||
comboboxItemSplitPressable: {
|
||||
flex: 1,
|
||||
alignSelf: "stretch",
|
||||
minWidth: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
paddingLeft: theme.spacing[3],
|
||||
paddingRight: theme.spacing[1],
|
||||
paddingVertical: theme.spacing[2],
|
||||
},
|
||||
comboboxItemActionSlot: {
|
||||
alignSelf: "stretch",
|
||||
},
|
||||
comboboxItemHovered: {
|
||||
backgroundColor: theme.colors.surface1,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createFloatingPanelHosts,
|
||||
type FloatingPanelHostRect,
|
||||
type MeasurableFloatingPanelHost,
|
||||
} from "./floating-panel-hosts";
|
||||
|
||||
function createHost(rect: FloatingPanelHostRect): MeasurableFloatingPanelHost {
|
||||
return {
|
||||
measureInWindow: (callback) => callback(rect.x, rect.y, rect.width, rect.height),
|
||||
};
|
||||
}
|
||||
|
||||
const WORKSPACE_RECT: FloatingPanelHostRect = { x: 10, y: 20, width: 800, height: 600 };
|
||||
const RETAINED_VIEWPORT: FloatingPanelHostRect = { x: 0, y: 0, width: 1200, height: 900 };
|
||||
|
||||
describe("floating panel hosts", () => {
|
||||
it("measures the newest host registered under the name", async () => {
|
||||
const hosts = createFloatingPanelHosts();
|
||||
hosts.register("workspace", createHost(WORKSPACE_RECT));
|
||||
hosts.register("workspace", createHost(RETAINED_VIEWPORT));
|
||||
|
||||
expect(await hosts.measure("workspace")).toEqual(RETAINED_VIEWPORT);
|
||||
});
|
||||
|
||||
it("keeps measuring a survivor after the newest host unregisters", async () => {
|
||||
const hosts = createFloatingPanelHosts();
|
||||
const unregisterSurvivor = hosts.register("workspace", createHost(WORKSPACE_RECT));
|
||||
const unregisterNewest = hosts.register("workspace", createHost(RETAINED_VIEWPORT));
|
||||
|
||||
unregisterNewest();
|
||||
|
||||
expect(await hosts.measure("workspace")).toEqual(WORKSPACE_RECT);
|
||||
unregisterSurvivor();
|
||||
});
|
||||
|
||||
it("returns null once every host under the name is gone", async () => {
|
||||
const hosts = createFloatingPanelHosts();
|
||||
const unregisterFirst = hosts.register("workspace", createHost(WORKSPACE_RECT));
|
||||
const unregisterSecond = hosts.register("workspace", createHost(RETAINED_VIEWPORT));
|
||||
|
||||
unregisterFirst();
|
||||
unregisterSecond();
|
||||
|
||||
expect(await hosts.measure("workspace")).toBeNull();
|
||||
});
|
||||
|
||||
it("skips hosts that are not laid out", async () => {
|
||||
const hosts = createFloatingPanelHosts();
|
||||
hosts.register("workspace", createHost(WORKSPACE_RECT));
|
||||
hosts.register("workspace", createHost({ x: 0, y: 0, width: 0, height: 0 }));
|
||||
|
||||
expect(await hosts.measure("workspace")).toEqual(WORKSPACE_RECT);
|
||||
});
|
||||
|
||||
it("ignores a repeated unregister of the same host", async () => {
|
||||
const hosts = createFloatingPanelHosts();
|
||||
const unregister = hosts.register("workspace", createHost(WORKSPACE_RECT));
|
||||
|
||||
unregister();
|
||||
unregister();
|
||||
|
||||
expect(await hosts.measure("workspace")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
export interface FloatingPanelHostRect {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface MeasurableFloatingPanelHost {
|
||||
measureInWindow(callback: (x: number, y: number, width: number, height: number) => void): void;
|
||||
}
|
||||
|
||||
export interface FloatingPanelHosts<T extends MeasurableFloatingPanelHost> {
|
||||
register(name: string, host: T): () => void;
|
||||
measure(name: string): Promise<FloatingPanelHostRect | null>;
|
||||
}
|
||||
|
||||
function measureHost(host: MeasurableFloatingPanelHost): Promise<FloatingPanelHostRect> {
|
||||
return new Promise((resolve) => {
|
||||
host.measureInWindow((x, y, width, height) => resolve({ x, y, width, height }));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hosts are addressed by name, and one name can have several live hosts: a workspace
|
||||
* screen mounts its own host while retained copies of that screen stay mounted. Track
|
||||
* every host so unmounting one leaves the others measurable.
|
||||
*/
|
||||
export function createFloatingPanelHosts<
|
||||
T extends MeasurableFloatingPanelHost,
|
||||
>(): FloatingPanelHosts<T> {
|
||||
const hostsByName = new Map<string, T[]>();
|
||||
|
||||
function register(name: string, host: T): () => void {
|
||||
const hosts = hostsByName.get(name) ?? [];
|
||||
hostsByName.set(name, hosts);
|
||||
hosts.push(host);
|
||||
|
||||
return () => {
|
||||
const index = hosts.indexOf(host);
|
||||
if (index === -1) return;
|
||||
hosts.splice(index, 1);
|
||||
if (hosts.length === 0 && hostsByName.get(name) === hosts) {
|
||||
hostsByName.delete(name);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function measure(name: string): Promise<FloatingPanelHostRect | null> {
|
||||
const hosts = hostsByName.get(name);
|
||||
if (!hosts || hosts.length === 0) return null;
|
||||
|
||||
const rects = await Promise.all(hosts.toReversed().map(measureHost));
|
||||
return rects.find((rect) => rect.width > 0 && rect.height > 0) ?? rects[0];
|
||||
}
|
||||
|
||||
return { register, measure };
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { Portal, PortalProvider } from "@gorhom/portal";
|
||||
import { FloatingPanelPortalHost, measureFloatingPanelPortalHost } from "./floating-panel-portal";
|
||||
|
||||
describe("Floating panel host lifetime", () => {
|
||||
test("removing the newest host preserves the surviving host measurement", async () => {
|
||||
const container = document.createElement("div");
|
||||
container.style.cssText = "position:relative;width:800px;height:600px";
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
function Content({ overlap }: { overlap: boolean }) {
|
||||
return (
|
||||
<PortalProvider shouldAddRootHost={false}>
|
||||
<FloatingPanelPortalHost name="workspace" />
|
||||
{overlap && <FloatingPanelPortalHost name="workspace" />}
|
||||
<Portal hostName="workspace" name="picker">
|
||||
<div data-testid="picker">Commands</div>
|
||||
</Portal>
|
||||
</PortalProvider>
|
||||
);
|
||||
}
|
||||
try {
|
||||
await act(async () => root.render(<Content overlap={true} />));
|
||||
expect(await measureFloatingPanelPortalHost("workspace")).toMatchObject({
|
||||
width: 800,
|
||||
height: 600,
|
||||
});
|
||||
await act(async () => root.render(<Content overlap={false} />));
|
||||
expect(await measureFloatingPanelPortalHost("workspace")).toMatchObject({
|
||||
width: 800,
|
||||
height: 600,
|
||||
});
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -8,32 +8,21 @@ import {
|
||||
} from "react";
|
||||
import { StyleSheet, View } from "react-native";
|
||||
import { PortalHost } from "@gorhom/portal";
|
||||
import {
|
||||
createFloatingPanelHosts,
|
||||
type FloatingPanelHostRect,
|
||||
} from "@/components/ui/floating-panel-hosts";
|
||||
|
||||
export const DEFAULT_FLOATING_PANEL_PORTAL_HOST = "content-floating-panels";
|
||||
|
||||
const FloatingPanelPortalHostNameContext = createContext(DEFAULT_FLOATING_PANEL_PORTAL_HOST);
|
||||
|
||||
interface Rect {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
const portalHosts = createFloatingPanelHosts<View>();
|
||||
|
||||
const portalHostElements = new Map<string, View>();
|
||||
|
||||
function measureElement(element: View): Promise<Rect> {
|
||||
return new Promise((resolve) => {
|
||||
element.measureInWindow((x, y, width, height) => {
|
||||
resolve({ x, y, width, height });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function measureFloatingPanelPortalHost(name: string): Promise<Rect | null> {
|
||||
const element = portalHostElements.get(name);
|
||||
if (!element) return Promise.resolve(null);
|
||||
return measureElement(element);
|
||||
export function measureFloatingPanelPortalHost(
|
||||
name: string,
|
||||
): Promise<FloatingPanelHostRect | null> {
|
||||
return portalHosts.measure(name);
|
||||
}
|
||||
|
||||
export function FloatingPanelPortalHostNameProvider({
|
||||
@@ -64,12 +53,7 @@ export function FloatingPanelPortalHost({
|
||||
useEffect(() => {
|
||||
const host = hostRef.current;
|
||||
if (!host) return undefined;
|
||||
portalHostElements.set(name, host);
|
||||
return () => {
|
||||
if (portalHostElements.get(name) === host) {
|
||||
portalHostElements.delete(name);
|
||||
}
|
||||
};
|
||||
return portalHosts.register(name, host);
|
||||
}, [name]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -345,6 +345,7 @@ export const ar: TranslationResources = {
|
||||
viewDiagram: "عرض المخطط",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "نسخ الاقتباس",
|
||||
copyCode: "نسخ الرمز",
|
||||
copyTurn: "نسخ بدوره",
|
||||
copyMessage: "انسخ الرسالة",
|
||||
|
||||
@@ -344,6 +344,7 @@ export const en = {
|
||||
viewDiagram: "View diagram",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copy quote",
|
||||
copyCode: "Copy code",
|
||||
copyTurn: "Copy turn",
|
||||
copyMessage: "Copy message",
|
||||
|
||||
@@ -350,6 +350,7 @@ export const es: TranslationResources = {
|
||||
viewDiagram: "Ver diagrama",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copiar cita",
|
||||
copyCode: "Copiar código",
|
||||
copyTurn: "Copiar turno",
|
||||
copyMessage: "Copiar mensaje",
|
||||
|
||||
@@ -350,6 +350,7 @@ export const fr: TranslationResources = {
|
||||
viewDiagram: "Afficher le diagramme",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copier la citation",
|
||||
copyCode: "Copier le code",
|
||||
copyTurn: "Copier l’échange",
|
||||
copyMessage: "Copier le message",
|
||||
|
||||
@@ -350,6 +350,7 @@ export const ja: TranslationResources = {
|
||||
viewDiagram: "図を表示",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "引用をコピー",
|
||||
copyCode: "コードをコピー",
|
||||
copyTurn: "ターンをコピー",
|
||||
copyMessage: "メッセージをコピー",
|
||||
|
||||
@@ -346,6 +346,7 @@ export const ko: TranslationResources = {
|
||||
viewDiagram: "다이어그램 보기",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "인용문 복사",
|
||||
copyCode: "코드 복사",
|
||||
copyTurn: "턴 복사",
|
||||
copyMessage: "메시지 복사",
|
||||
|
||||
@@ -349,6 +349,7 @@ export const ptBR: TranslationResources = {
|
||||
viewDiagram: "Ver diagrama",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Copiar citação",
|
||||
copyCode: "Copiar código",
|
||||
copyTurn: "Copiar turno",
|
||||
copyMessage: "Copiar mensagem",
|
||||
|
||||
@@ -349,6 +349,7 @@ export const ru: TranslationResources = {
|
||||
viewDiagram: "Показать диаграмму",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "Копировать цитату",
|
||||
copyCode: "Скопировать код",
|
||||
copyTurn: "Скопировать ответ",
|
||||
copyMessage: "Копировать сообщение",
|
||||
|
||||
@@ -345,6 +345,7 @@ export const zhCN: TranslationResources = {
|
||||
viewDiagram: "查看图表",
|
||||
},
|
||||
actions: {
|
||||
copyQuote: "复制引用",
|
||||
copyCode: "复制代码",
|
||||
copyTurn: "复制回合",
|
||||
copyMessage: "复制消息",
|
||||
|
||||
@@ -22,7 +22,10 @@ import {
|
||||
|
||||
export const TERMINAL_INPUT_CONTEXT_MENU_HIDDEN = true;
|
||||
export const TERMINAL_INPUT_HITBOX_SIZE = 1;
|
||||
/** Matched by the Android hardware keyboard module to claim arrow keys for this input. */
|
||||
/**
|
||||
* Matched on Android by the hardware keyboard module to claim arrow keys for this input, and by
|
||||
* PaseoTerminal to keep the keyboard from learning what is typed here, such as passwords.
|
||||
*/
|
||||
export const TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input";
|
||||
|
||||
export interface TerminalTextInputChange {
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
createSelectionClipboardContent,
|
||||
type MarkdownClipboardEnvironment,
|
||||
type RichClipboardWriter,
|
||||
writeClipboardContent,
|
||||
writeMarkdownToRichClipboard,
|
||||
} from "./rich-clipboard";
|
||||
|
||||
@@ -15,9 +16,9 @@ interface RecordingClipboard {
|
||||
}
|
||||
|
||||
function createRecordingClipboard(
|
||||
options: { supportsHtml?: boolean; richWriteFails?: boolean } = {},
|
||||
options: { supportsHtml?: boolean; richWriteFails?: boolean; plainWriteResult?: unknown } = {},
|
||||
): RecordingClipboard {
|
||||
const { supportsHtml = true, richWriteFails = false } = options;
|
||||
const { supportsHtml = true, richWriteFails = false, plainWriteResult } = options;
|
||||
const richWrites: Array<Record<"text/plain" | "text/html", Blob>> = [];
|
||||
const plainTexts: string[] = [];
|
||||
|
||||
@@ -35,6 +36,7 @@ function createRecordingClipboard(
|
||||
richWriter,
|
||||
writePlainText: async (text) => {
|
||||
plainTexts.push(text);
|
||||
return plainWriteResult;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -185,3 +187,44 @@ describe("writeMarkdownToRichClipboard", () => {
|
||||
expect(clipboard.richWrites).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("writeClipboardContent", () => {
|
||||
const content = { plainText: "_raw_ draft", html: "<p>\\_raw\\_ draft</p>" };
|
||||
|
||||
it("writes both flavors and reports the write", async () => {
|
||||
const clipboard = createRecordingClipboard();
|
||||
|
||||
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(true);
|
||||
|
||||
const written = clipboard.richWrites[0];
|
||||
if (!written) {
|
||||
throw new Error("Expected rich clipboard data to be written");
|
||||
}
|
||||
await expect(written["text/plain"].text()).resolves.toBe(content.plainText);
|
||||
await expect(written["text/html"].text()).resolves.toBe(content.html);
|
||||
});
|
||||
|
||||
it("falls back to the plain flavor when the rich write fails", async () => {
|
||||
const clipboard = createRecordingClipboard({ richWriteFails: true });
|
||||
|
||||
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(true);
|
||||
|
||||
expect(clipboard.plainTexts).toEqual([content.plainText]);
|
||||
});
|
||||
|
||||
it("reports a plain write the host refused", async () => {
|
||||
const clipboard = createRecordingClipboard({ supportsHtml: false, plainWriteResult: false });
|
||||
|
||||
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("propagates a plain write that throws", async () => {
|
||||
const environment: MarkdownClipboardEnvironment = {
|
||||
writePlainText: async () => {
|
||||
throw new Error("clipboard denied");
|
||||
},
|
||||
};
|
||||
|
||||
await expect(writeClipboardContent(content, environment)).rejects.toThrow("clipboard denied");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -86,19 +86,30 @@ export async function writeMarkdownToRichClipboard(
|
||||
markdown: string,
|
||||
environment: MarkdownClipboardEnvironment,
|
||||
): Promise<void> {
|
||||
await writeClipboardContent(createMarkdownClipboardContent(markdown), environment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes both flavors, or `plainText` alone where the host has no rich clipboard.
|
||||
* Resolves false when the host refused the write.
|
||||
*/
|
||||
export async function writeClipboardContent(
|
||||
content: MarkdownClipboardContent,
|
||||
environment: MarkdownClipboardEnvironment,
|
||||
): Promise<boolean> {
|
||||
if (environment.richWriter?.supportsHtml()) {
|
||||
const content = createMarkdownClipboardContent(markdown);
|
||||
try {
|
||||
await environment.richWriter.write({
|
||||
"text/plain": new Blob([content.plainText], { type: "text/plain" }),
|
||||
"text/html": new Blob([content.html], { type: "text/html" }),
|
||||
});
|
||||
return;
|
||||
return true;
|
||||
} catch {
|
||||
// Fall through to the plain-text path. Some webviews expose rich clipboard
|
||||
// APIs but deny writes depending on focus, permissions, or browser policy.
|
||||
}
|
||||
}
|
||||
|
||||
await environment.writePlainText(markdown);
|
||||
// Expo resolves false for a write the host refused, instead of rejecting.
|
||||
return (await environment.writePlainText(content.plainText)) !== false;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/cli",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"description": "Paseo CLI - control your AI coding agents from the command line",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
@@ -29,9 +29,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.0.0",
|
||||
"@getpaseo/client": "0.17.2",
|
||||
"@getpaseo/protocol": "0.17.2",
|
||||
"@getpaseo/server": "0.17.2",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/server": "0.17.3",
|
||||
"chalk": "^5.3.0",
|
||||
"commander": "^12.0.0",
|
||||
"mime-types": "^2.1.35",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/client",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"description": "Paseo client SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -49,8 +49,8 @@
|
||||
"measure:diff-materialization": "tsx scripts/measure-diff-materialization.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@getpaseo/protocol": "0.17.2",
|
||||
"@getpaseo/relay": "0.17.2",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@getpaseo/relay": "0.17.3",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/desktop",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"private": true,
|
||||
"description": "Paseo desktop app (Electron wrapper)",
|
||||
"homepage": "https://paseo.sh",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/expo-two-way-audio",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"description": "Native module for two way audio streaming",
|
||||
"keywords": [
|
||||
"ExpoTwoWayAudio",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/highlight",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
"dist",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/plugin",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"description": "Paseo plugin SDK package",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
@@ -78,8 +78,8 @@
|
||||
"use-sync-external-store": "^1.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/client": "0.17.2",
|
||||
"@getpaseo/protocol": "0.17.2",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"@types/node": "^20.9.0",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.2.3",
|
||||
@@ -89,8 +89,8 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@getpaseo/client": "0.17.2",
|
||||
"@getpaseo/protocol": "0.17.2",
|
||||
"@getpaseo/client": "0.17.3",
|
||||
"@getpaseo/protocol": "0.17.3",
|
||||
"react": ">=19.1.0 <20",
|
||||
"react-native": ">=0.81.5",
|
||||
"zod": "^4.4.3"
|
||||
|
||||
@@ -46,6 +46,7 @@ import {
|
||||
type ProviderEvent,
|
||||
type ProviderInput,
|
||||
type ProviderLaunch,
|
||||
type ProviderModel,
|
||||
type ProviderPermissionResponse,
|
||||
type ProviderPersistence,
|
||||
type ProviderSessionConfig,
|
||||
@@ -694,7 +695,10 @@ class AcpRuntime {
|
||||
this.nativeSessionId = response.sessionId;
|
||||
this.modes = response.modes ?? null;
|
||||
this.configOptions = response.configOptions ?? [];
|
||||
const catalog = toProviderCatalog(this.modes, this.configOptions);
|
||||
let catalog = toProviderCatalog(this.modes, this.configOptions);
|
||||
if (this.options.options.acpOptions?.perModelThinkingOptions) {
|
||||
catalog = { ...catalog, models: await this.modelsWithOwnThinkingOptions(catalog) };
|
||||
}
|
||||
const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
|
||||
if (!autoAcceptMode) return catalog;
|
||||
return {
|
||||
@@ -704,6 +708,33 @@ class AcpRuntime {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects each model in the discovery session to read the thinking options the agent lists for
|
||||
* it, then selects the opening model again for the transformers that run after discovery.
|
||||
*/
|
||||
private async modelsWithOwnThinkingOptions(catalog: ProviderCatalog): Promise<ProviderModel[]> {
|
||||
const models: ProviderModel[] = [];
|
||||
for (const model of catalog.models) {
|
||||
await this.selectModel(model.id);
|
||||
const { thinkingOptions, thinkingOption } = toProviderConfigState(
|
||||
this.modes,
|
||||
this.configOptions,
|
||||
);
|
||||
models.push({
|
||||
...model,
|
||||
thinkingOptions: [...thinkingOptions],
|
||||
defaultThinkingOptionId: thinkingOption,
|
||||
});
|
||||
}
|
||||
if (catalog.defaultModel) await this.selectModel(catalog.defaultModel);
|
||||
return models;
|
||||
}
|
||||
|
||||
private async selectModel(model: string): Promise<void> {
|
||||
if (selectedValue(modelOption(this.configOptions)) === model) return;
|
||||
await this.applyNativeConfigChange({ target: "model", value: model });
|
||||
}
|
||||
|
||||
async prompt(input: Extract<ProviderInput, { type: "session.prompt" }>): Promise<void> {
|
||||
if (this.closing || this.processFailed || this.deferredRetirement) {
|
||||
throw new Error("ACP session is closed");
|
||||
|
||||
@@ -65,6 +65,24 @@ async function waitForEvent(
|
||||
return events.find(predicate)!;
|
||||
}
|
||||
|
||||
interface ModelThinking {
|
||||
id: string;
|
||||
thinkingOptions?: readonly { id: string }[];
|
||||
defaultThinkingOptionId?: string;
|
||||
}
|
||||
|
||||
function modelThinking(model: ModelThinking) {
|
||||
return {
|
||||
id: model.id,
|
||||
thinkingOptions: model.thinkingOptions?.map(optionId),
|
||||
defaultThinkingOptionId: model.defaultThinkingOptionId,
|
||||
};
|
||||
}
|
||||
|
||||
function optionId(option: { id: string }): string {
|
||||
return option.id;
|
||||
}
|
||||
|
||||
type AcpRequestMessage = Extract<AcpStreamMessage, { id: string | number | null; method: string }>;
|
||||
|
||||
interface ConnectorInstance {
|
||||
@@ -1997,6 +2015,70 @@ lines.on("line", (line) => {
|
||||
},
|
||||
);
|
||||
|
||||
it("discovers each model's own thinking options when the agent describes only the selected model", async () => {
|
||||
const executable = await fakeAcp(`const readline = require("node:readline");
|
||||
const lines = readline.createInterface({ input: process.stdin });
|
||||
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
||||
const levels = (values) => values.map((value) => ({ name: value[0].toUpperCase() + value.slice(1), value }));
|
||||
const thinking = {
|
||||
neon: { currentValue: "high", options: levels(["low", "high", "xhigh"]) },
|
||||
carbon: { currentValue: "medium", options: levels(["low", "medium", "high"]) },
|
||||
};
|
||||
let model = "neon";
|
||||
const options = () => [
|
||||
{ id: "model", name: "Model", category: "model", type: "select", currentValue: model, options: [{ name: "Neon", value: "neon" }, { name: "Carbon", value: "carbon" }, { name: "Orchestrator", value: "orchestrator" }] },
|
||||
...(thinking[model] ? [{ id: "thought_level", name: "Thinking", category: "thought_level", type: "select", ...thinking[model] }] : []),
|
||||
];
|
||||
lines.on("line", (line) => {
|
||||
const message = JSON.parse(line);
|
||||
if (message.method === "initialize") send({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} } });
|
||||
else if (message.method === "session/new") send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "native-1", modes: null, configOptions: options() } });
|
||||
else if (message.method === "session/set_config_option") {
|
||||
if (message.params.configId === "model") model = message.params.value;
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { configOptions: options() } });
|
||||
}
|
||||
});`);
|
||||
let modelSeenByTransformer: unknown;
|
||||
const registration = runAcpProvider({
|
||||
id: "test-acp",
|
||||
label: "Test ACP",
|
||||
command: [process.execPath, executable],
|
||||
acpOptions: { perModelThinkingOptions: true },
|
||||
transformers: [
|
||||
{
|
||||
async discover(catalog, { config }) {
|
||||
modelSeenByTransformer = (await config.read()).model;
|
||||
return catalog;
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
const connection = await registration.connect({ versions: [1], capabilities: [] });
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send({ type: "catalog", requestId: "catalog-1", cwd: process.cwd() });
|
||||
const event = await waitForEvent(
|
||||
events,
|
||||
(candidate) => candidate.type === "catalog" || candidate.type === "request.failed",
|
||||
);
|
||||
if (event.type !== "catalog") throw new Error(`Expected catalog, got ${event.type}`);
|
||||
expect(event.catalog.defaultModel).toBe("neon");
|
||||
expect(event.catalog.models.map(modelThinking)).toEqual([
|
||||
{ id: "neon", thinkingOptions: ["low", "high", "xhigh"], defaultThinkingOptionId: "high" },
|
||||
{
|
||||
id: "carbon",
|
||||
thinkingOptions: ["low", "medium", "high"],
|
||||
defaultThinkingOptionId: "medium",
|
||||
},
|
||||
{ id: "orchestrator", thinkingOptions: [], defaultThinkingOptionId: undefined },
|
||||
]);
|
||||
expect(modelSeenByTransformer).toBe("neon");
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("selects the model control when an agent files several controls under the model category", async () => {
|
||||
const executable = await fakeAcp(`const readline = require("node:readline");
|
||||
const lines = readline.createInterface({ input: process.stdin });
|
||||
|
||||
@@ -49,6 +49,11 @@ export interface AcpOptions {
|
||||
startupTimeoutMs?: number;
|
||||
/** Global discovery initializes ACP but returns an empty catalog without opening a session. */
|
||||
workspaceOnlyCatalog?: boolean;
|
||||
/**
|
||||
* For an agent that lists thinking options only for the selected model: discovery selects each
|
||||
* model in turn and records the thinking options the agent lists for it, or none.
|
||||
*/
|
||||
perModelThinkingOptions?: boolean;
|
||||
waitForInitialCommands?: boolean;
|
||||
initialCommandsTimeoutMs?: number;
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@getpaseo/protocol",
|
||||
"version": "0.17.2",
|
||||
"version": "0.17.3",
|
||||
"description": "Paseo shared protocol schemas and wire types",
|
||||
"license": "Apache-2.0",
|
||||
"files": [
|
||||
|
||||
@@ -94,6 +94,19 @@ describe("Hub session protocol", () => {
|
||||
expect(SessionOutboundMessageSchema.parse(response)).toEqual(response);
|
||||
});
|
||||
|
||||
test("round-trips the working directory on named-agent validation", () => {
|
||||
const request = {
|
||||
type: "hub.execution.agent.validate.request",
|
||||
requestId: "validate-workspace",
|
||||
provider: "opencode",
|
||||
model: "workspace-model",
|
||||
cwd: "/workspace",
|
||||
};
|
||||
|
||||
expect(SessionInboundMessageSchema.parse(request)).toEqual(request);
|
||||
expect(SessionInboundMessageSchema.safeParse({ ...request, cwd: 123 }).success).toBe(false);
|
||||
});
|
||||
|
||||
test("accepts the Hub execution create request", () => {
|
||||
const message = {
|
||||
type: "hub.execution.agent.create.request",
|
||||
|
||||
@@ -3465,6 +3465,7 @@ export const HubExecutionAgentValidateRequestSchema = z.object({
|
||||
type: z.literal("hub.execution.agent.validate.request"),
|
||||
requestId: z.string(),
|
||||
provider: z.string(),
|
||||
cwd: z.string().optional(),
|
||||
model: z.string().optional(),
|
||||
modeId: z.string().optional(),
|
||||
thinkingOptionId: z.string().optional(),
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Native assets the postinstall script downloads (see postinstall.mjs).
|
||||
/cpp/highlight/vendor/grammars/
|
||||
/cpp/highlight/vendor/tree-sitter/
|
||||
/ios/vendor/
|
||||
/ios/vendor.staging/
|
||||
/ios/vendor.backup/
|
||||
|
||||
# Android build output when Gradle builds this library from source.
|
||||
/android/.cxx/
|
||||
/android/.gradle/
|
||||
@@ -0,0 +1,43 @@
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026 Lucide Icons and Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
The following Lucide icons are derived from the Feather project:
|
||||
|
||||
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
|
||||
|
||||
The MIT License (MIT) (for the icons listed above)
|
||||
|
||||
Copyright (c) 2013-present Cole Bemis
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,20 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Software Mansion
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,287 @@
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/b1efabc5-37df-4ddc-8fbb-6f587fdcb5e6">
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://github.com/user-attachments/assets/eb844f3b-4b63-4327-bf5e-569e4573dedc">
|
||||
<img alt="Enriched Markdown by Software Mansion" src="https://github.com/user-attachments/assets/b1efabc5-37df-4ddc-8fbb-6f587fdcb5e6">
|
||||
</picture>
|
||||
<a href="https://swm-delivery.com/www/delivery/ck-slug.php?zoneid=zone-gh-react-native-enriched-1&n=1"><img src="https://swm-delivery.com/www/images/zone-gh-react-native-enriched-1?n=1" /></a>
|
||||
<a href="https://swm-delivery.com/www/delivery/ck-slug.php?zoneid=zone-gh-react-native-enriched-2&n=1"><img src="https://swm-delivery.com/www/images/zone-gh-react-native-enriched-2?n=1" /></a>
|
||||
<a href="https://swm-delivery.com/www/delivery/ck-slug.php?zoneid=zone-gh-react-native-enriched-3&n=1"><img src="https://swm-delivery.com/www/images/zone-gh-react-native-enriched-3?n=1" /></a>
|
||||
|
||||
# react-native-enriched-markdown
|
||||
|
||||
`react-native-enriched-markdown` is a powerful React Native library that renders Markdown content as native text and provides a rich text input with Markdown output. It supports iOS, Android, macOS, and Web, and requires the New Architecture (Fabric) for native platforms.
|
||||
|
||||
### EnrichedMarkdownText
|
||||
|
||||
- ⚡ Fully native text rendering (no WebView)
|
||||
- 🌐 Web support via [react-native-web](https://necolas.github.io/react-native-web/) + [md4c](https://github.com/mity/md4c) compiled to WebAssembly
|
||||
- 🎯 High-performance Markdown parsing with [md4c](https://github.com/mity/md4c)
|
||||
- 📐 CommonMark standard compliant
|
||||
- 📊 GitHub Flavored Markdown (GFM)
|
||||
- 🧮 LaTeX math rendering (block `$$...$$` with `flavor="github"`, inline `$...$` in all flavors)
|
||||
- 🔀 [Markdown Streaming](../../docs-md/MARKDOWN_STREAMING.md) support (via [react-native-streamdown](https://github.com/software-mansion-labs/react-native-streamdown))
|
||||
- 🎨 Fully customizable styles for all elements
|
||||
- ✨ Text selection and copy support
|
||||
- 📌 Custom text selection context menu items
|
||||
- 🔗 Interactive link handling with [per-URL-pattern styling](../../docs-md/MENTIONS.md#link-variants-styling) (`linkVariants`)
|
||||
- 💊 [Native link pills](../../docs-md/MENTIONS.md#native-link-pills) — links as rounded chips with an icon and label, per URL pattern or per link (iOS, Android)
|
||||
- 📎 [Long-press menus for links](../../docs-md/API_REFERENCE.md#linkcontextmenuitems) with your own items per URL pattern (`linkContextMenuItems`, iOS 17+)
|
||||
- 👤 Renders mentions as styled links (compatible with `EnrichedMarkdownTextInput` mention output)
|
||||
- 🙈 Spoiler text with animated particle overlay and tap-to-reveal
|
||||
- 🖼️ Native image interactions (iOS: Copy, Save to Camera Roll)
|
||||
- 🎬 Native video playback — block-level videos via HTML `<video>` tag
|
||||
- 🌐 Native platform features (Translate, Look Up, Search Web, Share)
|
||||
- 🗣️ Accessibility support (VoiceOver on iOS, TalkBack on Android, semantic HTML on web)
|
||||
- 🔄 Full RTL (right-to-left) support including text, lists, blockquotes, tables, and task lists
|
||||
|
||||
### EnrichedMarkdownTextInput
|
||||
|
||||
- ✏️ Rich text input with Markdown output
|
||||
- 🕹️ Imperative API for toggling styles and managing links
|
||||
- 📋 Native context menu with formatting submenu
|
||||
- 🔍 Real-time style state detection
|
||||
- 🔗 Auto-link detection with customizable regex
|
||||
- 🔄 Smart copy/paste with Markdown preservation
|
||||
- 🎨 Customizable bold, italic, and link colors
|
||||
- 👤 [Mentions](../../docs-md/MENTIONS.md) with configurable indicators, suggestion lifecycle events, and per-pattern link styling
|
||||
|
||||
Since 2012 [Software Mansion](https://swmansion.com) is a software agency with experience in building web and mobile apps. We are Core React Native Contributors and experts in dealing with all kinds of React Native issues.
|
||||
We can help you build your next dream product –
|
||||
[Hire us](https://swmansion.com/contact/projects?utm_source=react-native-enriched-markdown&utm_medium=readme).
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Prerequisites](#prerequisites)
|
||||
- [Installation](#installation)
|
||||
- [Native assets (install-time download)](../../docs-md/NATIVE_ASSETS.md)
|
||||
- [EnrichedMarkdownText](#enrichedmarkdowntext-1)
|
||||
- [Usage](../../docs-md/TEXT.md#usage)
|
||||
- [Supported Markdown Elements](../../docs-md/TEXT.md#supported-markdown-elements)
|
||||
- [Copy Options](../../docs-md/TEXT.md#copy-options)
|
||||
- [Accessibility](../../docs-md/TEXT.md#accessibility)
|
||||
- [RTL Support](../../docs-md/TEXT.md#rtl-support)
|
||||
- [Customizing Styles](../../docs-md/TEXT.md#customizing-styles)
|
||||
- [LaTeX Math](../../docs-md/LATEX_MATH.md)
|
||||
- [Image Caching](../../docs-md/IMAGE_CACHING.md)
|
||||
- [Markdown Streaming](../../docs-md/MARKDOWN_STREAMING.md)
|
||||
- [EnrichedMarkdownTextInput](#enrichedmarkdowntextinput-1)
|
||||
- [Usage](../../docs-md/INPUT.md#usage)
|
||||
- [Inline Styles](../../docs-md/INPUT.md#inline-styles)
|
||||
- [Links](../../docs-md/INPUT.md#links)
|
||||
- [Auto-Link Detection](../../docs-md/INPUT.md#auto-link-detection)
|
||||
- [Mentions](../../docs-md/MENTIONS.md)
|
||||
- [Style Detection](../../docs-md/INPUT.md#style-detection)
|
||||
- [Other Events](../../docs-md/INPUT.md#other-events)
|
||||
- [Customizing Styles](../../docs-md/INPUT.md#customizing-enrichedmarkdowntextinput--styles)
|
||||
- [API Reference](#api-reference)
|
||||
- [Testing with Jest](../../docs-md/TESTING.md)
|
||||
- [Web Support](../../docs-md/WEB.md)
|
||||
- [macOS Support](../../docs-md/MACOS.md)
|
||||
- [Compatibility Table](#compatibility-table)
|
||||
- [Contributing](#contributing)
|
||||
- [Future Plans](#future-plans)
|
||||
- [License](#license)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
**Native (iOS / Android / macOS)**
|
||||
|
||||
- Requires [the React Native New Architecture (Fabric)](https://reactnative.dev/architecture/landing-page)
|
||||
- See [Compatibility Table](#compatibility-table) for supported React Native versions
|
||||
- macOS support via [react-native-macos](https://github.com/microsoft/react-native-macos) `0.81+`
|
||||
|
||||
**Web**
|
||||
|
||||
- Requires [`react-native-web`](https://necolas.github.io/react-native-web/) and Metro (or another bundler with `.web.tsx` platform resolution)
|
||||
- No New Architecture requirement — the web renderer runs entirely in JavaScript via WebAssembly
|
||||
- Only `EnrichedMarkdownText` is supported on web (`EnrichedMarkdownTextInput` is native-only)
|
||||
- LaTeX math requires the optional [`katex`](https://katex.org/) peer dependency
|
||||
|
||||
## Installation
|
||||
|
||||
### Web
|
||||
|
||||
No steps beyond having `react-native-web` configured. For LaTeX math, install the optional peer dependency:
|
||||
|
||||
```sh
|
||||
npm install katex
|
||||
# or
|
||||
yarn add katex
|
||||
```
|
||||
|
||||
See [Web Support](../../docs-md/WEB.md) for full setup details, supported features, and prop behaviour.
|
||||
|
||||
### Bare React Native app (iOS / Android)
|
||||
|
||||
#### 1. Install the library
|
||||
|
||||
```sh
|
||||
yarn add react-native-enriched-markdown
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> To try the latest features before they land in a stable release, install the nightly build:
|
||||
>
|
||||
> ```sh
|
||||
> yarn add react-native-enriched-markdown@nightly
|
||||
> ```
|
||||
>
|
||||
> Nightly versions are published to npm automatically and may contain breaking changes.
|
||||
|
||||
> [!NOTE]
|
||||
> On install, a `postinstall` script downloads the large native assets used by code highlighting
|
||||
> and iOS LaTeX math (kept out of the npm tarball to keep it ~1 MB). This needs network access to
|
||||
> `registry.npmjs.org` and `github.com`. If you install offline, with `--ignore-scripts`, or with
|
||||
> **pnpm** (which blocks dependency scripts by default), see
|
||||
> [Native assets](../../docs-md/NATIVE_ASSETS.md) for how to restore them.
|
||||
|
||||
#### Configuration
|
||||
|
||||
Add an `"enriched-markdown"` block to your app's `package.json` to configure which features are enabled:
|
||||
|
||||
```json
|
||||
{
|
||||
"enriched-markdown": {
|
||||
"enableCodeHighlight": true,
|
||||
"enableMath": true,
|
||||
"enableVideo": true,
|
||||
"codeHighlightLanguages": ["javascript", "typescript", "python", "swift", "kotlin"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Key | Type | Default | Description |
|
||||
|---|---|---|---|
|
||||
| `enableCodeHighlight` | `boolean` | `true` | Download and compile tree-sitter grammars for syntax highlighting |
|
||||
| `enableMath` | `boolean` | `true` | Download [RaTeX](https://ratex.lites.dev/) for LaTeX math rendering (iOS) and include the Maven dependency (Android) |
|
||||
| `enableVideo` | `boolean` | `true` | Enable native video playback. Adds Media3 ExoPlayer (~2-3 MB) on Android; uses built-in AVKit on iOS. Set to `false` to exclude the dependency |
|
||||
| `codeHighlightLanguages` | `string[]` | all default grammars | Subset of languages to compile (reduces binary size). Ignored when `enableCodeHighlight` is `false`; an empty array `[]` compiles none (same as disabling). |
|
||||
|
||||
Your app's `package.json` is the single source of truth. `postinstall` reads it to decide
|
||||
what to **download** into `node_modules`, and the native build (iOS podspec / Android
|
||||
`build.gradle`) reads it directly to decide what to **compile and link** — no Podfile ENV
|
||||
vars or `gradle.properties` edits needed. Changing a value takes effect on your next
|
||||
`pod install` / native rebuild; **enabling** a feature that was off also needs a reinstall
|
||||
(`npm install` / `npm rebuild react-native-enriched-markdown`) so its assets get downloaded.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **iOS applies config at `pod install`, not at build time.** After editing the `enriched-markdown`
|
||||
> block, run `pod install` (a plain `run-ios` reuses the previously resolved pod). When **disabling** a
|
||||
> feature that was already compiled in — or narrowing `codeHighlightLanguages` — also do a clean build
|
||||
> (`Product > Clean Build Folder`), since Xcode's incremental build can link a stale pod library.
|
||||
> Android reconfigures on every build and needs neither step.
|
||||
|
||||
> [!TIP]
|
||||
> If you don't use a feature, disabling it skips the download **and** excludes it from the native build.
|
||||
> See [Skipping the download](../../docs-md/NATIVE_ASSETS.md#skipping-the-download-opt-out) for details.
|
||||
|
||||
> [!NOTE]
|
||||
> **Monorepos:** the native build reads the **app's** `package.json` (the one next to
|
||||
> `ios/`/`android/`), so each app can enable/disable features independently. The download
|
||||
> opt-out is resolved where you run the install — usually the workspace root — so to skip a
|
||||
> download entirely, put the opt-out in the **root** `package.json`.
|
||||
|
||||
> [!NOTE]
|
||||
> Migrating from the Expo config plugin or the `ENV` / `gradle.properties` build flags? See
|
||||
> [Breaking changes](../../docs-md/BREAKING_CHANGES.md).
|
||||
|
||||
#### 2. Install iOS / macOS dependencies
|
||||
|
||||
The library includes native code so you will need to re-build the native app.
|
||||
|
||||
```sh
|
||||
# iOS
|
||||
cd ios && bundle install && bundle exec pod install
|
||||
|
||||
# macOS (react-native-macos)
|
||||
cd macos && bundle install && bundle exec pod install
|
||||
```
|
||||
|
||||
### Expo app
|
||||
|
||||
#### 1. Install the library
|
||||
|
||||
```sh
|
||||
npx expo install react-native-enriched-markdown
|
||||
```
|
||||
|
||||
#### 2. Run prebuild
|
||||
|
||||
The library includes native code so you will need to re-build the native app.
|
||||
|
||||
```sh
|
||||
npx expo prebuild
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The library won't work in Expo Go as it needs native changes.
|
||||
|
||||
> [!NOTE]
|
||||
> `npx expo install` runs the same `postinstall` asset download described under
|
||||
> [Native assets](../../docs-md/NATIVE_ASSETS.md); it needs network access and does not work with Yarn PnP.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **iOS: Save to Camera Roll**
|
||||
>
|
||||
> If your Markdown content includes images and you want users to save them to their photo library, add the following to your `Info.plist`:
|
||||
>
|
||||
> ```xml
|
||||
> <key>NSPhotoLibraryAddUsageDescription</key>
|
||||
> <string>This app needs access to your photo library to save images.</string>
|
||||
> ```
|
||||
|
||||
## EnrichedMarkdownText
|
||||
|
||||
See [EnrichedMarkdownText](../../docs-md/TEXT.md) for detailed documentation on usage examples, GFM tables, task lists, link handling, supported elements, copy options, accessibility, RTL support, and customizing styles. Mentions created by `EnrichedMarkdownTextInput` render as styled links — use [`linkVariants`](../../docs-md/MENTIONS.md#link-variants-styling) to customize their appearance.
|
||||
|
||||
## EnrichedMarkdownTextInput
|
||||
|
||||
See [EnrichedMarkdownTextInput](../../docs-md/INPUT.md) for detailed documentation on usage examples, inline styles, links, style detection, events, and customizing styles.
|
||||
|
||||
## API Reference
|
||||
|
||||
See the [API Reference](../../docs-md/API_REFERENCE.md) for a detailed overview of all the props, methods, and events available.
|
||||
|
||||
## Web Support
|
||||
|
||||
See [Web Support](../../docs-md/WEB.md) for details on supported features, web-specific prop behaviour, and known limitations.
|
||||
|
||||
## macOS Support
|
||||
|
||||
`react-native-enriched-markdown` supports macOS via [react-native-macos](https://github.com/microsoft/react-native-macos). See [macOS Support](../../docs-md/MACOS.md) for details on macOS-specific features, known limitations, and the example app.
|
||||
|
||||
## Future Plans
|
||||
|
||||
We're actively working on expanding the capabilities of `react-native-enriched-markdown`. Here's what's on the roadmap:
|
||||
|
||||
- `EnrichedMarkdownTextInput`: headings, lists, blockquotes, code blocks, inline images
|
||||
- `EnrichedMarkdownTextInput` web support
|
||||
- macOS: block math rendering, VoiceOver accessibility, tail fade-in animation
|
||||
- Web: spoiler text, streaming animation, configurable link `target`, copy options (Copy as Markdown, multi-format clipboard)
|
||||
|
||||
## Compatibility Table
|
||||
|
||||
| | 0.82 | 0.83 | 0.84 | 0.85 | 0.86 | 0.87 |
|
||||
| ----------- | :--: | :--: | :--: | :--: | :--: | :--: |
|
||||
| **nightly** | ⛔ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| **1.1.x** | ⛔ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| **1.0.x** | ⛔ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| **0.7.0** | ⛔ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| **0.6.0** | ⛔ | ✅ | ✅ | ✅ | ⛔ | ⛔ |
|
||||
| **0.5.0** | ⛔ | ✅ | ✅ | ✅ | ⛔ | ⛔ |
|
||||
| **0.4.x** | ✅ | ✅ | ✅ | ⛔ | ⛔ | ⛔ |
|
||||
| **0.3.0** | ✅ | ✅ | ✅ | ⛔ | ⛔ | ⛔ |
|
||||
|
||||
## Contributing
|
||||
|
||||
See the [contributing guide](../../CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
|
||||
|
||||
## License
|
||||
|
||||
`react-native-enriched-markdown` library is licensed under [The MIT License](../../LICENSE).
|
||||
|
||||
---
|
||||
|
||||
Built by [Software Mansion](https://swmansion.com/).
|
||||
|
||||
[<img width="128" height="69" alt="Software Mansion Logo" src="https://github.com/user-attachments/assets/f0e18471-a7aa-4e80-86ac-87686a86fe56" />](https://swmansion.com/)
|
||||
@@ -0,0 +1,150 @@
|
||||
require "json"
|
||||
|
||||
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
|
||||
|
||||
monorepo = File.exist?(File.expand_path("../core/EnrichedMarkdownCore.podspec", __dir__))
|
||||
cpp_root = monorepo ? "$(PODS_TARGET_SRCROOT)/../core/cpp" : "$(PODS_TARGET_SRCROOT)/cpp"
|
||||
|
||||
require File.join(__dir__, "cpp/highlight/code_highlight_podspec.rb")
|
||||
# In the monorepo the C++ (including tree-sitter highlighting) compiles in the
|
||||
# EnrichedMarkdownCore pod; only the published, core-less build compiles it here.
|
||||
code_highlight = monorepo ? EnrichedMarkdownCodeHighlight.disabled : EnrichedMarkdownCodeHighlight.config(__dir__)
|
||||
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "ReactNativeEnrichedMarkdown"
|
||||
s.version = package["version"]
|
||||
s.summary = package["description"]
|
||||
s.homepage = package["homepage"]
|
||||
s.license = package["license"]
|
||||
s.authors = package["author"]
|
||||
|
||||
s.platforms = { :ios => min_ios_version_supported, :osx => '14.0' }
|
||||
s.source = { :git => "https://github.com/software-mansion/enriched-markdown.git", :tag => "#{s.version}" }
|
||||
|
||||
if monorepo
|
||||
s.private_header_files = "ios/**/*.h"
|
||||
s.source_files = "ios/**/*.{h,m,mm,cpp,swift}"
|
||||
s.dependency "EnrichedMarkdownCore"
|
||||
else
|
||||
s.private_header_files = "ios/**/*.h", "cpp/**/*.{h,hpp}"
|
||||
s.source_files = ["ios/**/*.{h,m,mm,cpp,swift}", "cpp/md4c/*.{c,h}", "cpp/parser/*.{hpp,cpp}", "cpp/highlight/*.{hpp,cpp}"] + code_highlight[:source_files]
|
||||
s.preserve_paths = "cpp/highlight/vendor/**/*" if code_highlight[:enabled]
|
||||
end
|
||||
|
||||
# LaTeX math rendering (RaTeX, iOS only). RaTeX ships as a prebuilt static XCFramework
|
||||
# vendored under ios/vendor (restored by vendor/vendor-ratex.mjs at postinstall); it
|
||||
# links under CocoaPods default static linkage and needs neither `use_frameworks!` nor
|
||||
# SPM interop.
|
||||
#
|
||||
# The app package.json "enriched-markdown" block is the source of truth; ENV is a
|
||||
# deprecated fallback. `math_explicit` tracks an active opt-in (vs the implicit
|
||||
# default), which decides the missing-framework behavior below.
|
||||
config = EnrichedMarkdownConfig.consumer_config
|
||||
# "present" mirrors the code-highlight side (see code_highlight_podspec.rb, which
|
||||
# gates on grammars/.stamp): the vendor script writes ios/vendor/.stamp only after
|
||||
# the XCFramework, the four Swift sources, and the fonts have all landed and it
|
||||
# swaps the tree into place atomically. Gating on the XCFramework directory alone
|
||||
# would treat a half-finished download (framework extracted, Swift sources/fonts
|
||||
# still missing) as ready and compile the RaTeX bridge against sources that are not
|
||||
# there, failing several hundred lines into the pod build with an opaque Swift
|
||||
# "cannot find type 'RaTeXRenderer' in scope" (#745).
|
||||
ratex_dir = File.join(__dir__, 'ios/vendor')
|
||||
# File.file? (not File.exist?) so a stray .stamp/ directory can't pass the check and
|
||||
# reintroduce the #745 failure mode; the vendor script only ever writes it as a file.
|
||||
ratex_present = File.directory?(File.join(ratex_dir, 'RaTeX.xcframework')) &&
|
||||
File.file?(File.join(ratex_dir, '.stamp'))
|
||||
math_flag = ENV['ENRICHED_MARKDOWN_ENABLE_MATH']
|
||||
|
||||
if config.key?('enableMath')
|
||||
math_requested = config['enableMath'] != false
|
||||
math_explicit = math_requested
|
||||
if math_flag
|
||||
EnrichedMarkdownConfig.warn_once(:math_env, '[ReactNativeEnrichedMarkdown] DEPRECATED: ENV[\'ENRICHED_MARKDOWN_ENABLE_MATH\'] ' \
|
||||
'is ignored when "enriched-markdown".enableMath is set in your package.json.')
|
||||
end
|
||||
elsif math_flag
|
||||
EnrichedMarkdownConfig.warn_once(:math_env, '[ReactNativeEnrichedMarkdown] DEPRECATED: ENV[\'ENRICHED_MARKDOWN_ENABLE_MATH\'] ' \
|
||||
'will be removed in a future version. Configure via "enriched-markdown".enableMath in your package.json instead.')
|
||||
math_requested = math_flag == '1'
|
||||
math_explicit = math_requested
|
||||
else
|
||||
math_requested = true
|
||||
math_explicit = false
|
||||
end
|
||||
|
||||
# RaTeX is downloaded at postinstall and kept out of the tarball. Reconcile the
|
||||
# request with the vendored tree: an explicit opt-in with the tree missing or
|
||||
# incomplete fails loud; on by default but missing (a partial/failed download, or a
|
||||
# monorepo root opt-out) falls back to a clean build without math.
|
||||
enable_math = math_requested && ratex_present
|
||||
if !math_requested
|
||||
EnrichedMarkdownConfig.warn_once(:math_disabled, '[ReactNativeEnrichedMarkdown] LaTeX math disabled via ' \
|
||||
'"enriched-markdown".enableMath = false in your app package.json.')
|
||||
elsif !ratex_present
|
||||
if math_explicit
|
||||
raise '[ReactNativeEnrichedMarkdown] LaTeX math is enabled but the vendored RaTeX ' \
|
||||
'assets are missing or incomplete at ios/vendor (need RaTeX.xcframework, the core ' \
|
||||
'Swift sources, the fonts, and the .stamp the vendor script writes on success). ' \
|
||||
'Reinstall to fetch them: `npm rebuild react-native-enriched-markdown`. ' \
|
||||
'To disable math, set "enriched-markdown".enableMath = false in your app package.json. ' \
|
||||
'Troubleshooting: https://github.com/software-mansion/enriched-markdown/blob/main/docs-md/NATIVE_ASSETS.md'
|
||||
end
|
||||
EnrichedMarkdownConfig.warn_once(:math_disabled, '[ReactNativeEnrichedMarkdown] LaTeX math disabled: the vendored RaTeX ' \
|
||||
'assets were not found or are incomplete at ios/vendor. If this is unintended, re-run ' \
|
||||
'`node node_modules/react-native-enriched-markdown/postinstall.mjs`.')
|
||||
end
|
||||
|
||||
# The RaTeX XCFramework bundles its own module.modulemap and headers; never let the
|
||||
# broad ios/**/*.h and ios/**/*.swift globs treat its internals as pod sources.
|
||||
exclude = ["ios/vendor/RaTeX.xcframework/**/*"]
|
||||
# ios/math holds the RaTeX bridge; ios/vendor/*.swift are RaTeX's vendored core Swift
|
||||
# sources. Both compile into this pod's module only when math is enabled.
|
||||
exclude += ["ios/math/**/*.swift", "ios/vendor/*.swift"] unless enable_math
|
||||
s.exclude_files = exclude
|
||||
# Bounded decoding of native pill icons.
|
||||
s.frameworks = "ImageIO"
|
||||
|
||||
# Video playback (AVKit, built into iOS — no external framework or vendored asset).
|
||||
# Default on: consumers opt out via "enriched-markdown".enableVideo = false in package.json.
|
||||
enable_video = config.key?('enableVideo') ? config['enableVideo'] != false : true
|
||||
|
||||
preprocessor_defs = "$(inherited) MD4C_USE_UTF8=1#{code_highlight[:defines]}"
|
||||
if enable_video
|
||||
preprocessor_defs += ' ENRICHED_MARKDOWN_VIDEO=1'
|
||||
end
|
||||
if enable_math
|
||||
preprocessor_defs += ' ENRICHED_MARKDOWN_MATH=1'
|
||||
# enable_math already implies ratex_present, i.e. a complete vendored tree marked by
|
||||
# ios/vendor/.stamp (the reconciliation above raises on an explicit opt-in with a
|
||||
# missing/incomplete tree and disables the default-on path), so the vendored
|
||||
# references below always resolve.
|
||||
# Prebuilt static XCFramework (device + simulator[arm64,x86_64] + macOS). Vendored
|
||||
# rather than pulled via spm_dependency, which compiled RaTeX's Swift wrapper per
|
||||
# requested arch (breaking universal simulator builds, #527) and double-collected
|
||||
# its XCFramework signature during archive assembly (#491).
|
||||
s.vendored_frameworks = 'ios/vendor/RaTeX.xcframework'
|
||||
# RaTeXFontLoader.loadFromCocoaPodsBundle() resolves "RaTeXCoreFonts.bundle" by name,
|
||||
# so this resource-bundle name is load-bearing -- keep it exactly RaTeXCoreFonts.
|
||||
s.resource_bundles = { 'RaTeXCoreFonts' => ['ios/vendor/Fonts/*.ttf'] }
|
||||
end
|
||||
|
||||
pod_xcconfig = {
|
||||
'HEADER_SEARCH_PATHS' => ([
|
||||
"\"#{cpp_root}/md4c\"", "\"#{cpp_root}/parser\"", "\"#{cpp_root}/highlight\"",
|
||||
"\"$(PODS_TARGET_SRCROOT)/ios/internals\"", "\"$(PODS_TARGET_SRCROOT)/ios/input/internals\""
|
||||
] + code_highlight[:header_paths].map { |p| "\"$(PODS_TARGET_SRCROOT)/#{p}\"" }).join(" "),
|
||||
'GCC_PREPROCESSOR_DEFINITIONS' => preprocessor_defs,
|
||||
'CLANG_CXX_LANGUAGE_STANDARD' => 'c++17',
|
||||
'DEFINES_MODULE' => 'YES'
|
||||
}
|
||||
|
||||
# No EXCLUDED_ARCHS dance: the vendored simulator slice (ios-arm64_x86_64-simulator)
|
||||
# already contains x86_64, so universal simulator builds resolve on both arches.
|
||||
s.pod_target_xcconfig = pod_xcconfig
|
||||
|
||||
# No script phases: vendoring a single prebuilt XCFramework means there is no
|
||||
# spm_dependency-generated duplicate RaTeXFFI modulemap to strip, and only one
|
||||
# signature is collected during archive assembly, so nothing collides.
|
||||
|
||||
install_modules_dependencies(s)
|
||||
end
|
||||
@@ -0,0 +1,312 @@
|
||||
buildscript {
|
||||
ext.getExtOrDefault = {name ->
|
||||
return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['EnrichedMarkdown_' + name]
|
||||
}
|
||||
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath "com.android.tools.build:gradle:8.7.2"
|
||||
// noinspection DifferentKotlinGradleVersion
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${getExtOrDefault('kotlinVersion')}"
|
||||
}
|
||||
}
|
||||
|
||||
apply plugin: "com.android.library"
|
||||
// Android Gradle Plugin 9 ships built-in Kotlin support and applies the Kotlin
|
||||
// plugin itself. Applying it a second time fails the configuration phase with
|
||||
// "Cannot add extension with name 'kotlin'". Apply it only when AGP is not
|
||||
// providing Kotlin: AGP 8 and older, or AGP 9 with android.builtInKotlin=false.
|
||||
def shouldApplyKotlinPlugin() {
|
||||
def agpMajor = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')[0].toInteger()
|
||||
if (agpMajor <= 8) {
|
||||
return true
|
||||
}
|
||||
// AGP 10 removes the opt-out: built-in Kotlin is always active there.
|
||||
if (agpMajor >= 10) {
|
||||
return false
|
||||
}
|
||||
def propertyVal = providers.gradleProperty("android.builtInKotlin").orNull
|
||||
def builtInKotlinEnabled = propertyVal != null ? propertyVal.toBoolean() : true
|
||||
return !builtInKotlinEnabled
|
||||
}
|
||||
|
||||
if (shouldApplyKotlinPlugin()) {
|
||||
apply plugin: "kotlin-android"
|
||||
}
|
||||
|
||||
apply plugin: "com.facebook.react"
|
||||
|
||||
def getExtOrIntegerDefault(name) {
|
||||
return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties["EnrichedMarkdown_" + name]).toInteger()
|
||||
}
|
||||
|
||||
// The consumer app's package.json "enriched-markdown" block is the build-time source of
|
||||
// truth for feature toggles (mirrors the iOS podspecs and react-native-worklets). It is
|
||||
// read from the Gradle build root -- "<app>/package.json", one level above the "<app>/android"
|
||||
// dir -- so in a monorepo it resolves to the app being built, not the workspace root.
|
||||
// Per-app config therefore works; the download side (postinstall) is a separate,
|
||||
// install-time decision. Gradle properties remain a deprecated fallback.
|
||||
def consumerConfig = [:]
|
||||
def consumerAppName = null
|
||||
def consumerPackageJson = new File(rootProject.projectDir, "../package.json")
|
||||
if (consumerPackageJson.exists()) {
|
||||
def parsed = new groovy.json.JsonSlurper().parse(consumerPackageJson)
|
||||
if (parsed instanceof Map) {
|
||||
if (parsed["enriched-markdown"] instanceof Map) {
|
||||
consumerConfig = parsed["enriched-markdown"]
|
||||
}
|
||||
consumerAppName = parsed["name"]
|
||||
}
|
||||
}
|
||||
|
||||
// Filesystem-safe per-app slug: package.json "name", else the app directory name -- the
|
||||
// same source and fallback the iOS podspec uses (installation root's parent), so both
|
||||
// platforms derive an identical slug for the same app. It keys the per-app generated
|
||||
// code-highlight registry (generated-<slug>) below so the artifact layout matches iOS and
|
||||
// two monorepo apps with different custom language sets never share one dir.
|
||||
def consumerAppSlug = (consumerAppName ?: rootProject.projectDir.parentFile?.name ?: "app").toString()
|
||||
.replaceAll('[^A-Za-z0-9._-]+', '-').replaceAll('^-+|-+$', '')
|
||||
if (!consumerAppSlug) consumerAppSlug = "app"
|
||||
|
||||
// Video: package.json > default true. Android video uses Media3 ExoPlayer as a Maven
|
||||
// dependency. Disable via "enriched-markdown".enableVideo = false to save ~2-3 MB.
|
||||
def enableVideo = consumerConfig.containsKey("enableVideo") ? consumerConfig.enableVideo != false : true
|
||||
|
||||
// Math: package.json > gradle property (deprecated) > default true. Android math is a
|
||||
// Maven dependency (no downloaded asset), so the flag simply includes or excludes it --
|
||||
// there is nothing to be missing, hence no throw as on iOS.
|
||||
def mathProp = rootProject.findProperty("enrichedMarkdown.enableMath") ?: findProperty("enrichedMarkdown.enableMath")
|
||||
def enableMath
|
||||
if (consumerConfig.containsKey("enableMath")) {
|
||||
enableMath = consumerConfig.enableMath != false
|
||||
if (mathProp != null) {
|
||||
logger.warn("[ReactNativeEnrichedMarkdown] DEPRECATED: enrichedMarkdown.enableMath gradle property " +
|
||||
"is ignored when \"enriched-markdown\".enableMath is set in your package.json.")
|
||||
}
|
||||
} else if (mathProp != null) {
|
||||
logger.warn("[ReactNativeEnrichedMarkdown] DEPRECATED: enrichedMarkdown.enableMath gradle property " +
|
||||
"will be removed in a future version. Configure via \"enriched-markdown\".enableMath in your package.json instead.")
|
||||
enableMath = mathProp.toString().toBoolean()
|
||||
} else {
|
||||
enableMath = true
|
||||
}
|
||||
|
||||
// Default grammar set derived from the single source of truth,
|
||||
// vendor/grammar-versions.json (every grammar with default:true), so the compiled
|
||||
// grammars always match the registry gen-registry generates from the same
|
||||
// manifest. Resolved in both layouts like gen-registry.mjs below:
|
||||
// "../../../vendor" in the monorepo, "../cpp/highlight" when published.
|
||||
def grammarManifest = [
|
||||
new File(projectDir, "../../../vendor/grammar-versions.json"),
|
||||
new File(projectDir, "../cpp/highlight/grammar-versions.json"),
|
||||
].find { it.exists() }
|
||||
if (grammarManifest == null) {
|
||||
throw new GradleException("[code-highlight] grammar-versions.json not found; cannot resolve the default language set. Build from the monorepo or a published tarball.")
|
||||
}
|
||||
def defaultCodeHighlightLanguages = new groovy.json.JsonSlurper().parse(grammarManifest)
|
||||
.grammars.findAll { id, spec -> spec['default'] }.collect { id, spec -> id }
|
||||
// Code highlight enable: package.json > gradle property (deprecated) > default on.
|
||||
// `codeHighlightExplicit` tracks an active opt-in (vs the implicit default), which
|
||||
// decides the missing-grammars behavior below.
|
||||
def codeHighlightProp = rootProject.findProperty("enrichedMarkdown.enableCodeHighlight") ?: findProperty("enrichedMarkdown.enableCodeHighlight")
|
||||
def codeHighlightStamp = new File(projectDir, "../cpp/highlight/vendor/grammars/.stamp")
|
||||
def codeHighlightRequested
|
||||
def codeHighlightExplicit
|
||||
if (consumerConfig.containsKey("enableCodeHighlight")) {
|
||||
codeHighlightRequested = consumerConfig.enableCodeHighlight != false
|
||||
codeHighlightExplicit = codeHighlightRequested
|
||||
if (codeHighlightProp != null) {
|
||||
logger.warn("[ReactNativeEnrichedMarkdown] DEPRECATED: enrichedMarkdown.enableCodeHighlight gradle property " +
|
||||
"is ignored when \"enriched-markdown\".enableCodeHighlight is set in your package.json.")
|
||||
}
|
||||
} else if (codeHighlightProp != null) {
|
||||
logger.warn("[ReactNativeEnrichedMarkdown] DEPRECATED: enrichedMarkdown.enableCodeHighlight gradle property " +
|
||||
"will be removed in a future version. Configure via \"enriched-markdown\".enableCodeHighlight in your package.json instead.")
|
||||
codeHighlightRequested = codeHighlightProp.toString().toBoolean()
|
||||
codeHighlightExplicit = codeHighlightRequested
|
||||
} else {
|
||||
codeHighlightRequested = true
|
||||
codeHighlightExplicit = false
|
||||
}
|
||||
|
||||
// The grammars/.stamp marker is written only after every grammar source is fully vendored
|
||||
// at postinstall. An explicit opt-in with the grammars missing fails loud with the fix; on
|
||||
// by default but missing (a partial/failed download, or a monorepo root opt-out) falls back
|
||||
// to a clean no-op build. Gating on the stamp also keeps CMake from being fed missing sources.
|
||||
def enableCodeHighlight
|
||||
if (!codeHighlightRequested) {
|
||||
enableCodeHighlight = false
|
||||
} else if (codeHighlightStamp.exists()) {
|
||||
enableCodeHighlight = true
|
||||
} else if (codeHighlightExplicit) {
|
||||
throw new GradleException("[ReactNativeEnrichedMarkdown] code highlighting is enabled but the tree-sitter " +
|
||||
"grammars are not installed. Reinstall to fetch them: `npm rebuild react-native-enriched-markdown`. " +
|
||||
"To disable, set \"enriched-markdown\".enableCodeHighlight = false in your app package.json. " +
|
||||
"Troubleshooting: https://github.com/software-mansion/enriched-markdown/blob/main/docs-md/NATIVE_ASSETS.md")
|
||||
} else {
|
||||
enableCodeHighlight = false
|
||||
}
|
||||
|
||||
// Languages: package.json > gradle property (deprecated) > manifest defaults. An explicit
|
||||
// empty array disables all languages (codeHighlightActive below); only the default/property
|
||||
// paths fall back to the manifest set.
|
||||
def codeHighlightLanguagesProp = rootProject.findProperty("enrichedMarkdown.codeHighlightLanguages") ?: findProperty("enrichedMarkdown.codeHighlightLanguages")
|
||||
def codeHighlightLanguages
|
||||
if (consumerConfig.get("codeHighlightLanguages") instanceof List) {
|
||||
codeHighlightLanguages = consumerConfig.codeHighlightLanguages.collect { it.toString().trim() }.findAll { it }
|
||||
if (codeHighlightLanguagesProp != null) {
|
||||
logger.warn("[ReactNativeEnrichedMarkdown] DEPRECATED: enrichedMarkdown.codeHighlightLanguages gradle property " +
|
||||
"is ignored when \"enriched-markdown\".codeHighlightLanguages is set in your package.json.")
|
||||
}
|
||||
} else if (codeHighlightLanguagesProp) {
|
||||
logger.warn("[ReactNativeEnrichedMarkdown] DEPRECATED: enrichedMarkdown.codeHighlightLanguages gradle property " +
|
||||
"will be removed in a future version. Configure via \"enriched-markdown\".codeHighlightLanguages in your package.json instead.")
|
||||
codeHighlightLanguages = codeHighlightLanguagesProp.toString().split(",").collect { it.trim() }.findAll { it }
|
||||
} else {
|
||||
codeHighlightLanguages = defaultCodeHighlightLanguages
|
||||
}
|
||||
def codeHighlightActive = enableCodeHighlight && !codeHighlightLanguages.isEmpty()
|
||||
|
||||
android {
|
||||
namespace "com.swmansion.enriched.markdown"
|
||||
|
||||
compileSdkVersion getExtOrIntegerDefault("compileSdkVersion")
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion getExtOrIntegerDefault("minSdkVersion")
|
||||
targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
|
||||
consumerProguardFiles "consumer-rules.pro"
|
||||
buildConfigField "boolean", "ENABLE_MATH", "${enableMath}"
|
||||
buildConfigField "boolean", "ENABLE_VIDEO", "${enableVideo}"
|
||||
buildConfigField "boolean", "ENABLE_CODE_HIGHLIGHT", "${codeHighlightActive}"
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
buildConfig true
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.includeAndroidResources = true
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
}
|
||||
}
|
||||
|
||||
lintOptions {
|
||||
disable "GradleCompatible"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
main {
|
||||
java.srcDirs += [
|
||||
"generated/java",
|
||||
"generated/jni"
|
||||
]
|
||||
if (enableMath) {
|
||||
java.srcDirs += ["src/math/java"]
|
||||
}
|
||||
if (enableVideo) {
|
||||
java.srcDirs += ["src/video/java"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Code-block syntax highlighting (tree-sitter) native wiring. This module owns
|
||||
// no externalNativeBuild block: RN autolinking compiles src/main/jni/CMakeLists.txt
|
||||
// as part of the consumer app's native build, so the app -- not this library --
|
||||
// owns the CMake arguments. The enable flag + selected grammars therefore reach
|
||||
// CMake through a config file written here during configuration (before any
|
||||
// native build task runs) and include()d by CMakeLists.txt.
|
||||
def highlightConfigDir = new File(projectDir, "build/generated/highlight")
|
||||
highlightConfigDir.mkdirs()
|
||||
def highlightConfigFile = new File(highlightConfigDir, "highlight-config.cmake")
|
||||
if (codeHighlightActive) {
|
||||
def vendorDir = new File(projectDir, "../cpp/highlight/vendor").canonicalPath
|
||||
def committedGenerated = new File(vendorDir, "generated")
|
||||
def generatedDir
|
||||
if (codeHighlightLanguages.toSorted() == defaultCodeHighlightLanguages.toSorted() && committedGenerated.exists()) {
|
||||
// Common case: the committed default-set registry ships in-tree, no codegen.
|
||||
generatedDir = committedGenerated
|
||||
} else {
|
||||
// Custom language set: regenerate the registry from the vendored .scm files into a
|
||||
// per-app dir (generated-<slug>), mirroring iOS. Android rewrites this on every
|
||||
// gradle configure so it never had iOS's persistent clash, but keying per app keeps
|
||||
// the two platforms' artifact layout identical. (highlight-config.cmake itself stays
|
||||
// at the CMakeLists-fixed shared path and is rewritten each configure.)
|
||||
generatedDir = new File(highlightConfigDir, "generated-${consumerAppSlug}")
|
||||
generatedDir.mkdirs()
|
||||
def genScript = [
|
||||
new File(projectDir, "../../../vendor/gen-registry.mjs"),
|
||||
new File(projectDir, "../cpp/highlight/gen-registry.mjs"),
|
||||
].find { it.exists() }
|
||||
if (genScript == null) {
|
||||
throw new GradleException("enrichedMarkdown.codeHighlightLanguages is customized but vendor/gen-registry.mjs was not found. Use the default language set or build from the monorepo.")
|
||||
}
|
||||
// Run node directly via ProcessBuilder rather than Project.exec {}, which was
|
||||
// removed in Gradle 9. Runs at configuration time (before the native build),
|
||||
// and surfaces gen-registry's own stderr on failure.
|
||||
def genCmd = ["node", genScript.canonicalPath, "--vendor-dir", vendorDir,
|
||||
"--languages", codeHighlightLanguages.join(","), "--out", generatedDir.canonicalPath]
|
||||
def genProc = new ProcessBuilder(genCmd).redirectErrorStream(true).start()
|
||||
def genOut = genProc.inputStream.text
|
||||
def genExit = genProc.waitFor()
|
||||
if (genExit != 0) {
|
||||
throw new GradleException("[code-highlight] gen-registry.mjs failed (exit ${genExit}):\n${genOut}")
|
||||
}
|
||||
}
|
||||
highlightConfigFile.text = """\
|
||||
set(ENRICHED_MARKDOWN_CODE_HIGHLIGHT ON)
|
||||
set(ENRICHED_MARKDOWN_HIGHLIGHT_LANGUAGES "${codeHighlightLanguages.join(';')}")
|
||||
set(ENRICHED_MARKDOWN_HIGHLIGHT_GENERATED_DIR "${generatedDir.canonicalPath.replace('\\', '/')}")
|
||||
"""
|
||||
} else {
|
||||
highlightConfigFile.text = "set(ENRICHED_MARKDOWN_CODE_HIGHLIGHT OFF)\n"
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
google()
|
||||
}
|
||||
|
||||
def kotlin_version = getExtOrDefault("kotlinVersion")
|
||||
|
||||
dependencies {
|
||||
// JVM unit tests (Robolectric) for the library's Kotlin spans/renderers. Run with
|
||||
// `./gradlew :react-native-enriched-markdown:testDebugUnitTest` from an app that
|
||||
// autolinks this module (e.g. apps/react-native-example/android). Mirrors the
|
||||
// standalone @enriched-markdown/android test stack.
|
||||
testImplementation "junit:junit:4.13.2"
|
||||
testImplementation "org.robolectric:robolectric:4.14.1"
|
||||
implementation "com.facebook.react:react-android"
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
|
||||
// Baseline Profile installer for AOT compilation hints
|
||||
implementation "androidx.profileinstaller:profileinstaller:1.3.1"
|
||||
// LaTeX math rendering (optional — set enrichedMarkdown.enableMath=false in gradle.properties to exclude)
|
||||
if (enableMath) {
|
||||
implementation("io.github.erweixin:ratex-android:0.1.14")
|
||||
}
|
||||
// Video playback (optional — set "enriched-markdown".enableVideo = false in package.json to exclude)
|
||||
if (enableVideo) {
|
||||
implementation("androidx.media3:media3-exoplayer:1.6.0")
|
||||
implementation("androidx.media3:media3-ui:1.6.0")
|
||||
}
|
||||
}
|
||||
|
||||
react {
|
||||
jsRootDir = file("../src/")
|
||||
libraryName = "EnrichedMarkdownText"
|
||||
codegenJavaPackageName = "com.swmansion.enriched.markdown"
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# ProGuard/R8 consumer rules for react-native-enriched-markdown
|
||||
#
|
||||
# JNI: Classes accessed from C++ (jni-adapter.cpp) via FindClass/GetFieldID.
|
||||
# R8 cannot trace hardcoded string lookups in native code.
|
||||
|
||||
-keep class com.swmansion.enriched.markdown.parser.MarkdownASTNode { *; }
|
||||
-keep class com.swmansion.enriched.markdown.parser.MarkdownASTNode$NodeType { *; }
|
||||
-keep class com.swmansion.enriched.markdown.parser.Md4cFlags { *; }
|
||||
-keep class com.swmansion.enriched.markdown.parser.TextLinkMatching { *; }
|
||||
-keep class com.swmansion.enriched.markdown.utils.common.LinkRegexConfig { *; }
|
||||
|
||||
# Reflection: Math classes loaded via Class.forName when enableMath=true.
|
||||
-keep class com.swmansion.enriched.markdown.spans.MathInlineSpan { *; }
|
||||
-keep class com.swmansion.enriched.markdown.spans.MathInlinePlaceholderSpan { *; }
|
||||
-keep class com.swmansion.enriched.markdown.spans.MathMeasureHelper { *; }
|
||||
-keep class com.swmansion.enriched.markdown.views.MathContainerView { *; }
|
||||
-keep class com.swmansion.enriched.markdown.renderer.MathInlineRenderer { *; }
|
||||
|
||||
# Reflection: Video container loaded via Class.forName when enableVideo=true.
|
||||
-keep class com.swmansion.enriched.markdown.segments.VideoContainerView { *; }
|
||||
|
||||
# RaTeX uses JNI to instantiate Java objects from native code.
|
||||
# R8 cannot trace these lookups and will strip or rename the referenced classes.
|
||||
-keep class io.ratex.** { *; }
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GeneratePropsJavaDelegate.js
|
||||
*/
|
||||
|
||||
package com.facebook.react.viewmanagers;
|
||||
|
||||
import android.view.View;
|
||||
import androidx.annotation.Nullable;
|
||||
import com.facebook.react.bridge.ColorPropConverter;
|
||||
import com.facebook.react.bridge.ReadableArray;
|
||||
import com.facebook.react.bridge.ReadableMap;
|
||||
import com.facebook.react.uimanager.BaseViewManager;
|
||||
import com.facebook.react.uimanager.BaseViewManagerDelegate;
|
||||
import com.facebook.react.uimanager.LayoutShadowNode;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public class EnrichedMarkdownManagerDelegate<T extends View, U extends BaseViewManager<T, ? extends LayoutShadowNode> & EnrichedMarkdownManagerInterface<T>> extends BaseViewManagerDelegate<T, U> {
|
||||
public EnrichedMarkdownManagerDelegate(U viewManager) {
|
||||
super(viewManager);
|
||||
}
|
||||
@Override
|
||||
public void setProperty(T view, String propName, @Nullable Object value) {
|
||||
switch (propName) {
|
||||
case "markdown":
|
||||
mViewManager.setMarkdown(view, value == null ? null : (String) value);
|
||||
break;
|
||||
case "markdownStyle":
|
||||
mViewManager.setMarkdownStyle(view, (ReadableMap) value);
|
||||
break;
|
||||
case "enableImagePress":
|
||||
mViewManager.setEnableImagePress(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "enableTaskListItemToggle":
|
||||
mViewManager.setEnableTaskListItemToggle(view, value == null ? true : (boolean) value);
|
||||
break;
|
||||
case "enableCodeBlockPress":
|
||||
mViewManager.setEnableCodeBlockPress(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "enableBlockContextMenu":
|
||||
mViewManager.setEnableBlockContextMenu(view, value == null ? true : (boolean) value);
|
||||
break;
|
||||
case "enableLinkPreview":
|
||||
mViewManager.setEnableLinkPreview(view, value == null ? true : (boolean) value);
|
||||
break;
|
||||
case "selectable":
|
||||
mViewManager.setSelectable(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "selectionColor":
|
||||
mViewManager.setSelectionColor(view, ColorPropConverter.getColor(value, view.getContext()));
|
||||
break;
|
||||
case "selectionHandleColor":
|
||||
mViewManager.setSelectionHandleColor(view, ColorPropConverter.getColor(value, view.getContext()));
|
||||
break;
|
||||
case "md4cFlags":
|
||||
mViewManager.setMd4cFlags(view, (ReadableMap) value);
|
||||
break;
|
||||
case "isGFM":
|
||||
mViewManager.setIsGFM(view, value == null ? true : (boolean) value);
|
||||
break;
|
||||
case "allowFontScaling":
|
||||
mViewManager.setAllowFontScaling(view, value == null ? true : (boolean) value);
|
||||
break;
|
||||
case "maxFontSizeMultiplier":
|
||||
mViewManager.setMaxFontSizeMultiplier(view, value == null ? 0f : ((Double) value).floatValue());
|
||||
break;
|
||||
case "allowTrailingMargin":
|
||||
mViewManager.setAllowTrailingMargin(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "streamingAnimation":
|
||||
mViewManager.setStreamingAnimation(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "streamingConfig":
|
||||
mViewManager.setStreamingConfig(view, (ReadableMap) value);
|
||||
break;
|
||||
case "spoilerOverlay":
|
||||
mViewManager.setSpoilerOverlay(view, value == null ? "particles" : (String) value);
|
||||
break;
|
||||
case "contextMenuItems":
|
||||
mViewManager.setContextMenuItems(view, (ReadableArray) value);
|
||||
break;
|
||||
case "imageRequestHeaders":
|
||||
mViewManager.setImageRequestHeaders(view, (ReadableArray) value);
|
||||
break;
|
||||
case "linkPillContent":
|
||||
mViewManager.setLinkPillContent(view, (ReadableArray) value);
|
||||
break;
|
||||
case "linkRecognition":
|
||||
mViewManager.setLinkRecognition(view, (ReadableMap) value);
|
||||
break;
|
||||
case "linkContextMenuItems":
|
||||
mViewManager.setLinkContextMenuItems(view, (ReadableArray) value);
|
||||
break;
|
||||
case "selectionMenuConfig":
|
||||
mViewManager.setSelectionMenuConfig(view, (ReadableMap) value);
|
||||
break;
|
||||
case "accessibilityLabels":
|
||||
mViewManager.setAccessibilityLabels(view, (ReadableMap) value);
|
||||
break;
|
||||
case "textBreakStrategy":
|
||||
mViewManager.setTextBreakStrategy(view, value == null ? "highQuality" : (String) value);
|
||||
break;
|
||||
case "lineBreakStrategyIOS":
|
||||
mViewManager.setLineBreakStrategyIOS(view, value == null ? "none" : (String) value);
|
||||
break;
|
||||
case "writingDirection":
|
||||
mViewManager.setWritingDirection(view, value == null ? "first-strong" : (String) value);
|
||||
break;
|
||||
case "numberOfLines":
|
||||
mViewManager.setNumberOfLines(view, value == null ? 0 : ((Double) value).intValue());
|
||||
break;
|
||||
case "ellipsizeMode":
|
||||
mViewManager.setEllipsizeMode(view, value == null ? "tail" : (String) value);
|
||||
break;
|
||||
default:
|
||||
super.setProperty(view, propName, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GeneratePropsJavaInterface.js
|
||||
*/
|
||||
|
||||
package com.facebook.react.viewmanagers;
|
||||
|
||||
import android.view.View;
|
||||
import androidx.annotation.Nullable;
|
||||
import com.facebook.react.bridge.ReadableArray;
|
||||
import com.facebook.react.bridge.ReadableMap;
|
||||
import com.facebook.react.uimanager.ViewManagerWithGeneratedInterface;
|
||||
|
||||
public interface EnrichedMarkdownManagerInterface<T extends View> extends ViewManagerWithGeneratedInterface {
|
||||
void setMarkdown(T view, @Nullable String value);
|
||||
void setMarkdownStyle(T view, @Nullable ReadableMap value);
|
||||
void setEnableImagePress(T view, boolean value);
|
||||
void setEnableTaskListItemToggle(T view, boolean value);
|
||||
void setEnableCodeBlockPress(T view, boolean value);
|
||||
void setEnableBlockContextMenu(T view, boolean value);
|
||||
void setEnableLinkPreview(T view, boolean value);
|
||||
void setSelectable(T view, boolean value);
|
||||
void setSelectionColor(T view, @Nullable Integer value);
|
||||
void setSelectionHandleColor(T view, @Nullable Integer value);
|
||||
void setMd4cFlags(T view, @Nullable ReadableMap value);
|
||||
void setIsGFM(T view, boolean value);
|
||||
void setAllowFontScaling(T view, boolean value);
|
||||
void setMaxFontSizeMultiplier(T view, float value);
|
||||
void setAllowTrailingMargin(T view, boolean value);
|
||||
void setStreamingAnimation(T view, boolean value);
|
||||
void setStreamingConfig(T view, @Nullable ReadableMap value);
|
||||
void setSpoilerOverlay(T view, @Nullable String value);
|
||||
void setContextMenuItems(T view, @Nullable ReadableArray value);
|
||||
void setImageRequestHeaders(T view, @Nullable ReadableArray value);
|
||||
void setLinkPillContent(T view, @Nullable ReadableArray value);
|
||||
void setLinkRecognition(T view, @Nullable ReadableMap value);
|
||||
void setLinkContextMenuItems(T view, @Nullable ReadableArray value);
|
||||
void setSelectionMenuConfig(T view, @Nullable ReadableMap value);
|
||||
void setAccessibilityLabels(T view, @Nullable ReadableMap value);
|
||||
void setTextBreakStrategy(T view, @Nullable String value);
|
||||
void setLineBreakStrategyIOS(T view, @Nullable String value);
|
||||
void setWritingDirection(T view, @Nullable String value);
|
||||
void setNumberOfLines(T view, int value);
|
||||
void setEllipsizeMode(T view, @Nullable String value);
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GeneratePropsJavaDelegate.js
|
||||
*/
|
||||
|
||||
package com.facebook.react.viewmanagers;
|
||||
|
||||
import android.view.View;
|
||||
import androidx.annotation.Nullable;
|
||||
import com.facebook.react.bridge.ColorPropConverter;
|
||||
import com.facebook.react.bridge.ReadableArray;
|
||||
import com.facebook.react.bridge.ReadableMap;
|
||||
import com.facebook.react.uimanager.BaseViewManager;
|
||||
import com.facebook.react.uimanager.BaseViewManagerDelegate;
|
||||
import com.facebook.react.uimanager.LayoutShadowNode;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public class EnrichedMarkdownTextInputManagerDelegate<T extends View, U extends BaseViewManager<T, ? extends LayoutShadowNode> & EnrichedMarkdownTextInputManagerInterface<T>> extends BaseViewManagerDelegate<T, U> {
|
||||
public EnrichedMarkdownTextInputManagerDelegate(U viewManager) {
|
||||
super(viewManager);
|
||||
}
|
||||
@Override
|
||||
public void setProperty(T view, String propName, @Nullable Object value) {
|
||||
switch (propName) {
|
||||
case "defaultValue":
|
||||
mViewManager.setDefaultValue(view, value == null ? null : (String) value);
|
||||
break;
|
||||
case "placeholder":
|
||||
mViewManager.setPlaceholder(view, value == null ? null : (String) value);
|
||||
break;
|
||||
case "placeholderTextColor":
|
||||
mViewManager.setPlaceholderTextColor(view, ColorPropConverter.getColor(value, view.getContext()));
|
||||
break;
|
||||
case "editable":
|
||||
mViewManager.setEditable(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "autoFocus":
|
||||
mViewManager.setAutoFocus(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "scrollEnabled":
|
||||
mViewManager.setScrollEnabled(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "markdownShortcuts":
|
||||
mViewManager.setMarkdownShortcuts(view, (ReadableMap) value);
|
||||
break;
|
||||
case "autoCapitalize":
|
||||
mViewManager.setAutoCapitalize(view, value == null ? null : (String) value);
|
||||
break;
|
||||
case "multiline":
|
||||
mViewManager.setMultiline(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "cursorColor":
|
||||
mViewManager.setCursorColor(view, ColorPropConverter.getColor(value, view.getContext()));
|
||||
break;
|
||||
case "selectionColor":
|
||||
mViewManager.setSelectionColor(view, ColorPropConverter.getColor(value, view.getContext()));
|
||||
break;
|
||||
case "markdownStyle":
|
||||
mViewManager.setMarkdownStyle(view, (ReadableMap) value);
|
||||
break;
|
||||
case "color":
|
||||
mViewManager.setColor(view, ColorPropConverter.getColor(value, view.getContext()));
|
||||
break;
|
||||
case "fontSize":
|
||||
mViewManager.setFontSize(view, value == null ? 0f : ((Double) value).floatValue());
|
||||
break;
|
||||
case "lineHeight":
|
||||
mViewManager.setLineHeight(view, value == null ? 0f : ((Double) value).floatValue());
|
||||
break;
|
||||
case "fontFamily":
|
||||
mViewManager.setFontFamily(view, value == null ? null : (String) value);
|
||||
break;
|
||||
case "fontWeight":
|
||||
mViewManager.setFontWeight(view, value == null ? null : (String) value);
|
||||
break;
|
||||
case "isOnChangeMarkdownSet":
|
||||
mViewManager.setIsOnChangeMarkdownSet(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "contextMenuItems":
|
||||
mViewManager.setContextMenuItems(view, (ReadableArray) value);
|
||||
break;
|
||||
case "selectionMenuConfig":
|
||||
mViewManager.setSelectionMenuConfig(view, (ReadableMap) value);
|
||||
break;
|
||||
case "formatMenuConfig":
|
||||
mViewManager.setFormatMenuConfig(view, (ReadableMap) value);
|
||||
break;
|
||||
case "linkRegex":
|
||||
mViewManager.setLinkRegex(view, (ReadableMap) value);
|
||||
break;
|
||||
case "mentionIndicators":
|
||||
mViewManager.setMentionIndicators(view, (ReadableArray) value);
|
||||
break;
|
||||
case "writingDirection":
|
||||
mViewManager.setWritingDirection(view, value == null ? "first-strong" : (String) value);
|
||||
break;
|
||||
default:
|
||||
super.setProperty(view, propName, value);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void receiveCommand(T view, String commandName, ReadableArray args) {
|
||||
switch (commandName) {
|
||||
case "focus":
|
||||
mViewManager.focus(view);
|
||||
break;
|
||||
case "blur":
|
||||
mViewManager.blur(view);
|
||||
break;
|
||||
case "setValue":
|
||||
mViewManager.setValue(view, args.getString(0));
|
||||
break;
|
||||
case "setSelection":
|
||||
mViewManager.setSelection(view, args.getInt(0), args.getInt(1));
|
||||
break;
|
||||
case "toggleBold":
|
||||
mViewManager.toggleBold(view);
|
||||
break;
|
||||
case "toggleItalic":
|
||||
mViewManager.toggleItalic(view);
|
||||
break;
|
||||
case "toggleUnderline":
|
||||
mViewManager.toggleUnderline(view);
|
||||
break;
|
||||
case "toggleStrikethrough":
|
||||
mViewManager.toggleStrikethrough(view);
|
||||
break;
|
||||
case "toggleSpoiler":
|
||||
mViewManager.toggleSpoiler(view);
|
||||
break;
|
||||
case "toggleHeading":
|
||||
mViewManager.toggleHeading(view, args.getInt(0));
|
||||
break;
|
||||
case "toggleUnorderedList":
|
||||
mViewManager.toggleUnorderedList(view);
|
||||
break;
|
||||
case "toggleOrderedList":
|
||||
mViewManager.toggleOrderedList(view);
|
||||
break;
|
||||
case "indentList":
|
||||
mViewManager.indentList(view);
|
||||
break;
|
||||
case "outdentList":
|
||||
mViewManager.outdentList(view);
|
||||
break;
|
||||
case "setLink":
|
||||
mViewManager.setLink(view, args.getString(0));
|
||||
break;
|
||||
case "insertLink":
|
||||
mViewManager.insertLink(view, args.getString(0), args.getString(1));
|
||||
break;
|
||||
case "insertText":
|
||||
mViewManager.insertText(view, args.getString(0));
|
||||
break;
|
||||
case "insertMention":
|
||||
mViewManager.insertMention(view, args.getString(0), args.getString(1));
|
||||
break;
|
||||
case "startMention":
|
||||
mViewManager.startMention(view, args.getString(0));
|
||||
break;
|
||||
case "removeLink":
|
||||
mViewManager.removeLink(view);
|
||||
break;
|
||||
case "copyToClipboard":
|
||||
mViewManager.copyToClipboard(view);
|
||||
break;
|
||||
case "requestMarkdown":
|
||||
mViewManager.requestMarkdown(view, args.getInt(0));
|
||||
break;
|
||||
case "requestCaretRect":
|
||||
mViewManager.requestCaretRect(view, args.getInt(0));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GeneratePropsJavaInterface.js
|
||||
*/
|
||||
|
||||
package com.facebook.react.viewmanagers;
|
||||
|
||||
import android.view.View;
|
||||
import androidx.annotation.Nullable;
|
||||
import com.facebook.react.bridge.ReadableArray;
|
||||
import com.facebook.react.bridge.ReadableMap;
|
||||
import com.facebook.react.uimanager.ViewManagerWithGeneratedInterface;
|
||||
|
||||
public interface EnrichedMarkdownTextInputManagerInterface<T extends View> extends ViewManagerWithGeneratedInterface {
|
||||
void setDefaultValue(T view, @Nullable String value);
|
||||
void setPlaceholder(T view, @Nullable String value);
|
||||
void setPlaceholderTextColor(T view, @Nullable Integer value);
|
||||
void setEditable(T view, boolean value);
|
||||
void setAutoFocus(T view, boolean value);
|
||||
void setScrollEnabled(T view, boolean value);
|
||||
void setMarkdownShortcuts(T view, @Nullable ReadableMap value);
|
||||
void setAutoCapitalize(T view, @Nullable String value);
|
||||
void setMultiline(T view, boolean value);
|
||||
void setCursorColor(T view, @Nullable Integer value);
|
||||
void setSelectionColor(T view, @Nullable Integer value);
|
||||
void setMarkdownStyle(T view, @Nullable ReadableMap value);
|
||||
void setColor(T view, @Nullable Integer value);
|
||||
void setFontSize(T view, float value);
|
||||
void setLineHeight(T view, float value);
|
||||
void setFontFamily(T view, @Nullable String value);
|
||||
void setFontWeight(T view, @Nullable String value);
|
||||
void setIsOnChangeMarkdownSet(T view, boolean value);
|
||||
void setContextMenuItems(T view, @Nullable ReadableArray value);
|
||||
void setSelectionMenuConfig(T view, @Nullable ReadableMap value);
|
||||
void setFormatMenuConfig(T view, @Nullable ReadableMap value);
|
||||
void setLinkRegex(T view, @Nullable ReadableMap value);
|
||||
void setMentionIndicators(T view, @Nullable ReadableArray value);
|
||||
void setWritingDirection(T view, @Nullable String value);
|
||||
void focus(T view);
|
||||
void blur(T view);
|
||||
void setValue(T view, String markdown);
|
||||
void setSelection(T view, int start, int end);
|
||||
void toggleBold(T view);
|
||||
void toggleItalic(T view);
|
||||
void toggleUnderline(T view);
|
||||
void toggleStrikethrough(T view);
|
||||
void toggleSpoiler(T view);
|
||||
void toggleHeading(T view, int level);
|
||||
void toggleUnorderedList(T view);
|
||||
void toggleOrderedList(T view);
|
||||
void indentList(T view);
|
||||
void outdentList(T view);
|
||||
void setLink(T view, String url);
|
||||
void insertLink(T view, String text, String url);
|
||||
void insertText(T view, String text);
|
||||
void insertMention(T view, String displayText, String url);
|
||||
void startMention(T view, String indicator);
|
||||
void removeLink(T view);
|
||||
void copyToClipboard(T view);
|
||||
void requestMarkdown(T view, int requestId);
|
||||
void requestCaretRect(T view, int requestId);
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GeneratePropsJavaDelegate.js
|
||||
*/
|
||||
|
||||
package com.facebook.react.viewmanagers;
|
||||
|
||||
import android.view.View;
|
||||
import androidx.annotation.Nullable;
|
||||
import com.facebook.react.bridge.ColorPropConverter;
|
||||
import com.facebook.react.bridge.ReadableArray;
|
||||
import com.facebook.react.bridge.ReadableMap;
|
||||
import com.facebook.react.uimanager.BaseViewManager;
|
||||
import com.facebook.react.uimanager.BaseViewManagerDelegate;
|
||||
import com.facebook.react.uimanager.LayoutShadowNode;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public class EnrichedMarkdownTextManagerDelegate<T extends View, U extends BaseViewManager<T, ? extends LayoutShadowNode> & EnrichedMarkdownTextManagerInterface<T>> extends BaseViewManagerDelegate<T, U> {
|
||||
public EnrichedMarkdownTextManagerDelegate(U viewManager) {
|
||||
super(viewManager);
|
||||
}
|
||||
@Override
|
||||
public void setProperty(T view, String propName, @Nullable Object value) {
|
||||
switch (propName) {
|
||||
case "markdown":
|
||||
mViewManager.setMarkdown(view, value == null ? null : (String) value);
|
||||
break;
|
||||
case "markdownStyle":
|
||||
mViewManager.setMarkdownStyle(view, (ReadableMap) value);
|
||||
break;
|
||||
case "enableImagePress":
|
||||
mViewManager.setEnableImagePress(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "enableTaskListItemToggle":
|
||||
mViewManager.setEnableTaskListItemToggle(view, value == null ? true : (boolean) value);
|
||||
break;
|
||||
case "enableCodeBlockPress":
|
||||
mViewManager.setEnableCodeBlockPress(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "enableBlockContextMenu":
|
||||
mViewManager.setEnableBlockContextMenu(view, value == null ? true : (boolean) value);
|
||||
break;
|
||||
case "enableLinkPreview":
|
||||
mViewManager.setEnableLinkPreview(view, value == null ? true : (boolean) value);
|
||||
break;
|
||||
case "selectable":
|
||||
mViewManager.setSelectable(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "selectionColor":
|
||||
mViewManager.setSelectionColor(view, ColorPropConverter.getColor(value, view.getContext()));
|
||||
break;
|
||||
case "selectionHandleColor":
|
||||
mViewManager.setSelectionHandleColor(view, ColorPropConverter.getColor(value, view.getContext()));
|
||||
break;
|
||||
case "md4cFlags":
|
||||
mViewManager.setMd4cFlags(view, (ReadableMap) value);
|
||||
break;
|
||||
case "isGFM":
|
||||
mViewManager.setIsGFM(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "allowFontScaling":
|
||||
mViewManager.setAllowFontScaling(view, value == null ? true : (boolean) value);
|
||||
break;
|
||||
case "maxFontSizeMultiplier":
|
||||
mViewManager.setMaxFontSizeMultiplier(view, value == null ? 0f : ((Double) value).floatValue());
|
||||
break;
|
||||
case "allowTrailingMargin":
|
||||
mViewManager.setAllowTrailingMargin(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "streamingAnimation":
|
||||
mViewManager.setStreamingAnimation(view, value == null ? false : (boolean) value);
|
||||
break;
|
||||
case "streamingConfig":
|
||||
mViewManager.setStreamingConfig(view, (ReadableMap) value);
|
||||
break;
|
||||
case "spoilerOverlay":
|
||||
mViewManager.setSpoilerOverlay(view, value == null ? "particles" : (String) value);
|
||||
break;
|
||||
case "contextMenuItems":
|
||||
mViewManager.setContextMenuItems(view, (ReadableArray) value);
|
||||
break;
|
||||
case "imageRequestHeaders":
|
||||
mViewManager.setImageRequestHeaders(view, (ReadableArray) value);
|
||||
break;
|
||||
case "linkPillContent":
|
||||
mViewManager.setLinkPillContent(view, (ReadableArray) value);
|
||||
break;
|
||||
case "linkRecognition":
|
||||
mViewManager.setLinkRecognition(view, (ReadableMap) value);
|
||||
break;
|
||||
case "linkContextMenuItems":
|
||||
mViewManager.setLinkContextMenuItems(view, (ReadableArray) value);
|
||||
break;
|
||||
case "selectionMenuConfig":
|
||||
mViewManager.setSelectionMenuConfig(view, (ReadableMap) value);
|
||||
break;
|
||||
case "accessibilityLabels":
|
||||
mViewManager.setAccessibilityLabels(view, (ReadableMap) value);
|
||||
break;
|
||||
case "textBreakStrategy":
|
||||
mViewManager.setTextBreakStrategy(view, value == null ? "highQuality" : (String) value);
|
||||
break;
|
||||
case "lineBreakStrategyIOS":
|
||||
mViewManager.setLineBreakStrategyIOS(view, value == null ? "none" : (String) value);
|
||||
break;
|
||||
case "writingDirection":
|
||||
mViewManager.setWritingDirection(view, value == null ? "first-strong" : (String) value);
|
||||
break;
|
||||
case "numberOfLines":
|
||||
mViewManager.setNumberOfLines(view, value == null ? 0 : ((Double) value).intValue());
|
||||
break;
|
||||
case "ellipsizeMode":
|
||||
mViewManager.setEllipsizeMode(view, value == null ? "tail" : (String) value);
|
||||
break;
|
||||
default:
|
||||
super.setProperty(view, propName, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GeneratePropsJavaInterface.js
|
||||
*/
|
||||
|
||||
package com.facebook.react.viewmanagers;
|
||||
|
||||
import android.view.View;
|
||||
import androidx.annotation.Nullable;
|
||||
import com.facebook.react.bridge.ReadableArray;
|
||||
import com.facebook.react.bridge.ReadableMap;
|
||||
import com.facebook.react.uimanager.ViewManagerWithGeneratedInterface;
|
||||
|
||||
public interface EnrichedMarkdownTextManagerInterface<T extends View> extends ViewManagerWithGeneratedInterface {
|
||||
void setMarkdown(T view, @Nullable String value);
|
||||
void setMarkdownStyle(T view, @Nullable ReadableMap value);
|
||||
void setEnableImagePress(T view, boolean value);
|
||||
void setEnableTaskListItemToggle(T view, boolean value);
|
||||
void setEnableCodeBlockPress(T view, boolean value);
|
||||
void setEnableBlockContextMenu(T view, boolean value);
|
||||
void setEnableLinkPreview(T view, boolean value);
|
||||
void setSelectable(T view, boolean value);
|
||||
void setSelectionColor(T view, @Nullable Integer value);
|
||||
void setSelectionHandleColor(T view, @Nullable Integer value);
|
||||
void setMd4cFlags(T view, @Nullable ReadableMap value);
|
||||
void setIsGFM(T view, boolean value);
|
||||
void setAllowFontScaling(T view, boolean value);
|
||||
void setMaxFontSizeMultiplier(T view, float value);
|
||||
void setAllowTrailingMargin(T view, boolean value);
|
||||
void setStreamingAnimation(T view, boolean value);
|
||||
void setStreamingConfig(T view, @Nullable ReadableMap value);
|
||||
void setSpoilerOverlay(T view, @Nullable String value);
|
||||
void setContextMenuItems(T view, @Nullable ReadableArray value);
|
||||
void setImageRequestHeaders(T view, @Nullable ReadableArray value);
|
||||
void setLinkPillContent(T view, @Nullable ReadableArray value);
|
||||
void setLinkRecognition(T view, @Nullable ReadableMap value);
|
||||
void setLinkContextMenuItems(T view, @Nullable ReadableArray value);
|
||||
void setSelectionMenuConfig(T view, @Nullable ReadableMap value);
|
||||
void setAccessibilityLabels(T view, @Nullable ReadableMap value);
|
||||
void setTextBreakStrategy(T view, @Nullable String value);
|
||||
void setLineBreakStrategyIOS(T view, @Nullable String value);
|
||||
void setWritingDirection(T view, @Nullable String value);
|
||||
void setNumberOfLines(T view, int value);
|
||||
void setEllipsizeMode(T view, @Nullable String value);
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateComponentDescriptorCpp.js
|
||||
*/
|
||||
|
||||
#include "ComponentDescriptors.h"
|
||||
#include <react/renderer/core/ConcreteComponentDescriptor.h>
|
||||
#include <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
void EnrichedMarkdownTextSpec_registerComponentDescriptorsFromCodegen(
|
||||
std::shared_ptr<const ComponentDescriptorProviderRegistry> registry) {
|
||||
|
||||
}
|
||||
|
||||
} // namespace facebook::react
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateComponentDescriptorH.js
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "ShadowNodes.h"
|
||||
#include <react/renderer/core/ConcreteComponentDescriptor.h>
|
||||
#include <react/renderer/componentregistry/ComponentDescriptorProviderRegistry.h>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
|
||||
|
||||
void EnrichedMarkdownTextSpec_registerComponentDescriptorsFromCodegen(
|
||||
std::shared_ptr<const ComponentDescriptorProviderRegistry> registry);
|
||||
|
||||
} // namespace facebook::react
|
||||
+455
@@ -0,0 +1,455 @@
|
||||
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateEventEmitterCpp.js
|
||||
*/
|
||||
|
||||
#include "EventEmitters.h"
|
||||
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
void EnrichedMarkdownEventEmitter::onLinkPress(OnLinkPress event) const {
|
||||
dispatchEvent("linkPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "url", event.url);
|
||||
payload.setProperty(runtime, "sourceType", event.sourceType);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownEventEmitter::onLinkLongPress(OnLinkLongPress event) const {
|
||||
dispatchEvent("linkLongPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "url", event.url);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownEventEmitter::onImagePress(OnImagePress event) const {
|
||||
dispatchEvent("imagePress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "url", event.url);
|
||||
payload.setProperty(runtime, "altText", event.altText);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownEventEmitter::onTaskListItemPress(OnTaskListItemPress event) const {
|
||||
dispatchEvent("taskListItemPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "index", event.index);
|
||||
payload.setProperty(runtime, "checked", event.checked);
|
||||
payload.setProperty(runtime, "text", event.text);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownEventEmitter::onCopyPress(OnCopyPress event) const {
|
||||
dispatchEvent("copyPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "code", event.code);
|
||||
payload.setProperty(runtime, "language", event.language);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownEventEmitter::onCodeBlockPress(OnCodeBlockPress event) const {
|
||||
dispatchEvent("codeBlockPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "code", event.code);
|
||||
payload.setProperty(runtime, "language", event.language);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownEventEmitter::onLatexError(OnLatexError event) const {
|
||||
dispatchEvent("latexError", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "source", event.source);
|
||||
payload.setProperty(runtime, "message", event.message);
|
||||
payload.setProperty(runtime, "displayMode", event.displayMode);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownEventEmitter::onLinkContextMenuItemPress(OnLinkContextMenuItemPress event) const {
|
||||
dispatchEvent("linkContextMenuItemPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "url", event.url);
|
||||
payload.setProperty(runtime, "pattern", event.pattern);
|
||||
payload.setProperty(runtime, "itemText", event.itemText);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownEventEmitter::onContextMenuItemPress(OnContextMenuItemPress event) const {
|
||||
dispatchEvent("contextMenuItemPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "itemText", event.itemText);
|
||||
payload.setProperty(runtime, "selectedText", event.selectedText);
|
||||
payload.setProperty(runtime, "selectionStart", event.selectionStart);
|
||||
payload.setProperty(runtime, "selectionEnd", event.selectionEnd);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onChangeText(OnChangeText event) const {
|
||||
dispatchEvent("changeText", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "value", event.value);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onChangeMarkdown(OnChangeMarkdown event) const {
|
||||
dispatchEvent("changeMarkdown", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "value", event.value);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onChangeSelection(OnChangeSelection event) const {
|
||||
dispatchEvent("changeSelection", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "start", event.start);
|
||||
payload.setProperty(runtime, "end", event.end);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onInputKeyPress(OnInputKeyPress event) const {
|
||||
dispatchEvent("inputKeyPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "key", event.key);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onChangeState(OnChangeState event) const {
|
||||
dispatchEvent("changeState", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
{
|
||||
auto bold = jsi::Object(runtime);
|
||||
bold.setProperty(runtime, "isActive", event.bold.isActive);
|
||||
payload.setProperty(runtime, "bold", bold);
|
||||
}
|
||||
{
|
||||
auto italic = jsi::Object(runtime);
|
||||
italic.setProperty(runtime, "isActive", event.italic.isActive);
|
||||
payload.setProperty(runtime, "italic", italic);
|
||||
}
|
||||
{
|
||||
auto underline = jsi::Object(runtime);
|
||||
underline.setProperty(runtime, "isActive", event.underline.isActive);
|
||||
payload.setProperty(runtime, "underline", underline);
|
||||
}
|
||||
{
|
||||
auto strikethrough = jsi::Object(runtime);
|
||||
strikethrough.setProperty(runtime, "isActive", event.strikethrough.isActive);
|
||||
payload.setProperty(runtime, "strikethrough", strikethrough);
|
||||
}
|
||||
{
|
||||
auto spoiler = jsi::Object(runtime);
|
||||
spoiler.setProperty(runtime, "isActive", event.spoiler.isActive);
|
||||
payload.setProperty(runtime, "spoiler", spoiler);
|
||||
}
|
||||
{
|
||||
auto link = jsi::Object(runtime);
|
||||
link.setProperty(runtime, "isActive", event.link.isActive);
|
||||
link.setProperty(runtime, "destination", event.link.destination);
|
||||
payload.setProperty(runtime, "link", link);
|
||||
}
|
||||
{
|
||||
auto heading = jsi::Object(runtime);
|
||||
heading.setProperty(runtime, "isActive", event.heading.isActive);
|
||||
heading.setProperty(runtime, "level", event.heading.level);
|
||||
payload.setProperty(runtime, "heading", heading);
|
||||
}
|
||||
{
|
||||
auto unorderedList = jsi::Object(runtime);
|
||||
unorderedList.setProperty(runtime, "isActive", event.unorderedList.isActive);
|
||||
unorderedList.setProperty(runtime, "depth", event.unorderedList.depth);
|
||||
payload.setProperty(runtime, "unorderedList", unorderedList);
|
||||
}
|
||||
{
|
||||
auto orderedList = jsi::Object(runtime);
|
||||
orderedList.setProperty(runtime, "isActive", event.orderedList.isActive);
|
||||
orderedList.setProperty(runtime, "depth", event.orderedList.depth);
|
||||
payload.setProperty(runtime, "orderedList", orderedList);
|
||||
}
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onInputFocus(OnInputFocus event) const {
|
||||
dispatchEvent("inputFocus", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "target", event.target);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onInputBlur(OnInputBlur event) const {
|
||||
dispatchEvent("inputBlur", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "target", event.target);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onRequestMarkdownResult(OnRequestMarkdownResult event) const {
|
||||
dispatchEvent("requestMarkdownResult", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "requestId", event.requestId);
|
||||
payload.setProperty(runtime, "markdown", event.markdown);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onRequestCaretRectResult(OnRequestCaretRectResult event) const {
|
||||
dispatchEvent("requestCaretRectResult", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "requestId", event.requestId);
|
||||
payload.setProperty(runtime, "x", event.x);
|
||||
payload.setProperty(runtime, "y", event.y);
|
||||
payload.setProperty(runtime, "width", event.width);
|
||||
payload.setProperty(runtime, "height", event.height);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onCaretRectChange(OnCaretRectChange event) const {
|
||||
dispatchEvent("caretRectChange", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "x", event.x);
|
||||
payload.setProperty(runtime, "y", event.y);
|
||||
payload.setProperty(runtime, "width", event.width);
|
||||
payload.setProperty(runtime, "height", event.height);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onContextMenuItemPress(OnContextMenuItemPress event) const {
|
||||
dispatchEvent("contextMenuItemPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "itemText", event.itemText);
|
||||
payload.setProperty(runtime, "selectedText", event.selectedText);
|
||||
payload.setProperty(runtime, "selectionStart", event.selectionStart);
|
||||
payload.setProperty(runtime, "selectionEnd", event.selectionEnd);
|
||||
{
|
||||
auto styleState = jsi::Object(runtime);
|
||||
{
|
||||
auto bold = jsi::Object(runtime);
|
||||
bold.setProperty(runtime, "isActive", event.styleState.bold.isActive);
|
||||
styleState.setProperty(runtime, "bold", bold);
|
||||
}
|
||||
{
|
||||
auto italic = jsi::Object(runtime);
|
||||
italic.setProperty(runtime, "isActive", event.styleState.italic.isActive);
|
||||
styleState.setProperty(runtime, "italic", italic);
|
||||
}
|
||||
{
|
||||
auto underline = jsi::Object(runtime);
|
||||
underline.setProperty(runtime, "isActive", event.styleState.underline.isActive);
|
||||
styleState.setProperty(runtime, "underline", underline);
|
||||
}
|
||||
{
|
||||
auto strikethrough = jsi::Object(runtime);
|
||||
strikethrough.setProperty(runtime, "isActive", event.styleState.strikethrough.isActive);
|
||||
styleState.setProperty(runtime, "strikethrough", strikethrough);
|
||||
}
|
||||
{
|
||||
auto spoiler = jsi::Object(runtime);
|
||||
spoiler.setProperty(runtime, "isActive", event.styleState.spoiler.isActive);
|
||||
styleState.setProperty(runtime, "spoiler", spoiler);
|
||||
}
|
||||
{
|
||||
auto link = jsi::Object(runtime);
|
||||
link.setProperty(runtime, "isActive", event.styleState.link.isActive);
|
||||
link.setProperty(runtime, "destination", event.styleState.link.destination);
|
||||
styleState.setProperty(runtime, "link", link);
|
||||
}
|
||||
{
|
||||
auto heading = jsi::Object(runtime);
|
||||
heading.setProperty(runtime, "isActive", event.styleState.heading.isActive);
|
||||
heading.setProperty(runtime, "level", event.styleState.heading.level);
|
||||
styleState.setProperty(runtime, "heading", heading);
|
||||
}
|
||||
{
|
||||
auto unorderedList = jsi::Object(runtime);
|
||||
unorderedList.setProperty(runtime, "isActive", event.styleState.unorderedList.isActive);
|
||||
unorderedList.setProperty(runtime, "depth", event.styleState.unorderedList.depth);
|
||||
styleState.setProperty(runtime, "unorderedList", unorderedList);
|
||||
}
|
||||
{
|
||||
auto orderedList = jsi::Object(runtime);
|
||||
orderedList.setProperty(runtime, "isActive", event.styleState.orderedList.isActive);
|
||||
orderedList.setProperty(runtime, "depth", event.styleState.orderedList.depth);
|
||||
styleState.setProperty(runtime, "orderedList", orderedList);
|
||||
}
|
||||
payload.setProperty(runtime, "styleState", styleState);
|
||||
}
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onLinkDetected(OnLinkDetected event) const {
|
||||
dispatchEvent("linkDetected", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "text", event.text);
|
||||
payload.setProperty(runtime, "url", event.url);
|
||||
payload.setProperty(runtime, "start", event.start);
|
||||
payload.setProperty(runtime, "end", event.end);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onStartMention(OnStartMention event) const {
|
||||
dispatchEvent("startMention", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "indicator", event.indicator);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onChangeMention(OnChangeMention event) const {
|
||||
dispatchEvent("changeMention", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "indicator", event.indicator);
|
||||
payload.setProperty(runtime, "text", event.text);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextInputEventEmitter::onEndMention(OnEndMention event) const {
|
||||
dispatchEvent("endMention", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "indicator", event.indicator);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextEventEmitter::onLinkPress(OnLinkPress event) const {
|
||||
dispatchEvent("linkPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "url", event.url);
|
||||
payload.setProperty(runtime, "sourceType", event.sourceType);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextEventEmitter::onLinkLongPress(OnLinkLongPress event) const {
|
||||
dispatchEvent("linkLongPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "url", event.url);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextEventEmitter::onImagePress(OnImagePress event) const {
|
||||
dispatchEvent("imagePress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "url", event.url);
|
||||
payload.setProperty(runtime, "altText", event.altText);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextEventEmitter::onTaskListItemPress(OnTaskListItemPress event) const {
|
||||
dispatchEvent("taskListItemPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "index", event.index);
|
||||
payload.setProperty(runtime, "checked", event.checked);
|
||||
payload.setProperty(runtime, "text", event.text);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextEventEmitter::onCopyPress(OnCopyPress event) const {
|
||||
dispatchEvent("copyPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "code", event.code);
|
||||
payload.setProperty(runtime, "language", event.language);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextEventEmitter::onCodeBlockPress(OnCodeBlockPress event) const {
|
||||
dispatchEvent("codeBlockPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "code", event.code);
|
||||
payload.setProperty(runtime, "language", event.language);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextEventEmitter::onLatexError(OnLatexError event) const {
|
||||
dispatchEvent("latexError", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "source", event.source);
|
||||
payload.setProperty(runtime, "message", event.message);
|
||||
payload.setProperty(runtime, "displayMode", event.displayMode);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextEventEmitter::onLinkContextMenuItemPress(OnLinkContextMenuItemPress event) const {
|
||||
dispatchEvent("linkContextMenuItemPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "url", event.url);
|
||||
payload.setProperty(runtime, "pattern", event.pattern);
|
||||
payload.setProperty(runtime, "itemText", event.itemText);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
void EnrichedMarkdownTextEventEmitter::onContextMenuItemPress(OnContextMenuItemPress event) const {
|
||||
dispatchEvent("contextMenuItemPress", [event=std::move(event)](jsi::Runtime &runtime) {
|
||||
auto payload = jsi::Object(runtime);
|
||||
payload.setProperty(runtime, "itemText", event.itemText);
|
||||
payload.setProperty(runtime, "selectedText", event.selectedText);
|
||||
payload.setProperty(runtime, "selectionStart", event.selectionStart);
|
||||
payload.setProperty(runtime, "selectionEnd", event.selectionEnd);
|
||||
return payload;
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace facebook::react
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateEventEmitterH.js
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <react/renderer/components/view/ViewEventEmitter.h>
|
||||
|
||||
|
||||
namespace facebook::react {
|
||||
class EnrichedMarkdownEventEmitter : public ViewEventEmitter {
|
||||
public:
|
||||
using ViewEventEmitter::ViewEventEmitter;
|
||||
|
||||
struct OnLinkPress {
|
||||
std::string url;
|
||||
std::string sourceType;
|
||||
};
|
||||
|
||||
struct OnLinkLongPress {
|
||||
std::string url;
|
||||
};
|
||||
|
||||
struct OnImagePress {
|
||||
std::string url;
|
||||
std::string altText;
|
||||
};
|
||||
|
||||
struct OnTaskListItemPress {
|
||||
int index;
|
||||
bool checked;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
struct OnCopyPress {
|
||||
std::string code;
|
||||
std::string language;
|
||||
};
|
||||
|
||||
struct OnCodeBlockPress {
|
||||
std::string code;
|
||||
std::string language;
|
||||
};
|
||||
|
||||
struct OnLatexError {
|
||||
std::string source;
|
||||
std::string message;
|
||||
bool displayMode;
|
||||
};
|
||||
|
||||
struct OnLinkContextMenuItemPress {
|
||||
std::string url;
|
||||
std::string pattern;
|
||||
std::string itemText;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPress {
|
||||
std::string itemText;
|
||||
std::string selectedText;
|
||||
int selectionStart;
|
||||
int selectionEnd;
|
||||
};
|
||||
void onLinkPress(OnLinkPress value) const;
|
||||
|
||||
void onLinkLongPress(OnLinkLongPress value) const;
|
||||
|
||||
void onImagePress(OnImagePress value) const;
|
||||
|
||||
void onTaskListItemPress(OnTaskListItemPress value) const;
|
||||
|
||||
void onCopyPress(OnCopyPress value) const;
|
||||
|
||||
void onCodeBlockPress(OnCodeBlockPress value) const;
|
||||
|
||||
void onLatexError(OnLatexError value) const;
|
||||
|
||||
void onLinkContextMenuItemPress(OnLinkContextMenuItemPress value) const;
|
||||
|
||||
void onContextMenuItemPress(OnContextMenuItemPress value) const;
|
||||
};
|
||||
class EnrichedMarkdownTextInputEventEmitter : public ViewEventEmitter {
|
||||
public:
|
||||
using ViewEventEmitter::ViewEventEmitter;
|
||||
|
||||
struct OnChangeText {
|
||||
std::string value;
|
||||
};
|
||||
|
||||
struct OnChangeMarkdown {
|
||||
std::string value;
|
||||
};
|
||||
|
||||
struct OnChangeSelection {
|
||||
int start;
|
||||
int end;
|
||||
};
|
||||
|
||||
struct OnInputKeyPress {
|
||||
std::string key;
|
||||
};
|
||||
|
||||
struct OnChangeStateBold {
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct OnChangeStateItalic {
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct OnChangeStateUnderline {
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct OnChangeStateStrikethrough {
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct OnChangeStateSpoiler {
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct OnChangeStateLink {
|
||||
bool isActive;
|
||||
std::string destination;
|
||||
};
|
||||
|
||||
struct OnChangeStateHeading {
|
||||
bool isActive;
|
||||
int level;
|
||||
};
|
||||
|
||||
struct OnChangeStateUnorderedList {
|
||||
bool isActive;
|
||||
int depth;
|
||||
};
|
||||
|
||||
struct OnChangeStateOrderedList {
|
||||
bool isActive;
|
||||
int depth;
|
||||
};
|
||||
|
||||
struct OnChangeState {
|
||||
OnChangeStateBold bold;
|
||||
OnChangeStateItalic italic;
|
||||
OnChangeStateUnderline underline;
|
||||
OnChangeStateStrikethrough strikethrough;
|
||||
OnChangeStateSpoiler spoiler;
|
||||
OnChangeStateLink link;
|
||||
OnChangeStateHeading heading;
|
||||
OnChangeStateUnorderedList unorderedList;
|
||||
OnChangeStateOrderedList orderedList;
|
||||
};
|
||||
|
||||
struct OnInputFocus {
|
||||
int target;
|
||||
};
|
||||
|
||||
struct OnInputBlur {
|
||||
int target;
|
||||
};
|
||||
|
||||
struct OnRequestMarkdownResult {
|
||||
int requestId;
|
||||
std::string markdown;
|
||||
};
|
||||
|
||||
struct OnRequestCaretRectResult {
|
||||
int requestId;
|
||||
double x;
|
||||
double y;
|
||||
double width;
|
||||
double height;
|
||||
};
|
||||
|
||||
struct OnCaretRectChange {
|
||||
double x;
|
||||
double y;
|
||||
double width;
|
||||
double height;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPressStyleStateBold {
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPressStyleStateItalic {
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPressStyleStateUnderline {
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPressStyleStateStrikethrough {
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPressStyleStateSpoiler {
|
||||
bool isActive;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPressStyleStateLink {
|
||||
bool isActive;
|
||||
std::string destination;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPressStyleStateHeading {
|
||||
bool isActive;
|
||||
int level;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPressStyleStateUnorderedList {
|
||||
bool isActive;
|
||||
int depth;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPressStyleStateOrderedList {
|
||||
bool isActive;
|
||||
int depth;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPressStyleState {
|
||||
OnContextMenuItemPressStyleStateBold bold;
|
||||
OnContextMenuItemPressStyleStateItalic italic;
|
||||
OnContextMenuItemPressStyleStateUnderline underline;
|
||||
OnContextMenuItemPressStyleStateStrikethrough strikethrough;
|
||||
OnContextMenuItemPressStyleStateSpoiler spoiler;
|
||||
OnContextMenuItemPressStyleStateLink link;
|
||||
OnContextMenuItemPressStyleStateHeading heading;
|
||||
OnContextMenuItemPressStyleStateUnorderedList unorderedList;
|
||||
OnContextMenuItemPressStyleStateOrderedList orderedList;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPress {
|
||||
std::string itemText;
|
||||
std::string selectedText;
|
||||
int selectionStart;
|
||||
int selectionEnd;
|
||||
OnContextMenuItemPressStyleState styleState;
|
||||
};
|
||||
|
||||
struct OnLinkDetected {
|
||||
std::string text;
|
||||
std::string url;
|
||||
int start;
|
||||
int end;
|
||||
};
|
||||
|
||||
struct OnStartMention {
|
||||
std::string indicator;
|
||||
};
|
||||
|
||||
struct OnChangeMention {
|
||||
std::string indicator;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
struct OnEndMention {
|
||||
std::string indicator;
|
||||
};
|
||||
void onChangeText(OnChangeText value) const;
|
||||
|
||||
void onChangeMarkdown(OnChangeMarkdown value) const;
|
||||
|
||||
void onChangeSelection(OnChangeSelection value) const;
|
||||
|
||||
void onInputKeyPress(OnInputKeyPress value) const;
|
||||
|
||||
void onChangeState(OnChangeState value) const;
|
||||
|
||||
void onInputFocus(OnInputFocus value) const;
|
||||
|
||||
void onInputBlur(OnInputBlur value) const;
|
||||
|
||||
void onRequestMarkdownResult(OnRequestMarkdownResult value) const;
|
||||
|
||||
void onRequestCaretRectResult(OnRequestCaretRectResult value) const;
|
||||
|
||||
void onCaretRectChange(OnCaretRectChange value) const;
|
||||
|
||||
void onContextMenuItemPress(OnContextMenuItemPress value) const;
|
||||
|
||||
void onLinkDetected(OnLinkDetected value) const;
|
||||
|
||||
void onStartMention(OnStartMention value) const;
|
||||
|
||||
void onChangeMention(OnChangeMention value) const;
|
||||
|
||||
void onEndMention(OnEndMention value) const;
|
||||
};
|
||||
class EnrichedMarkdownTextEventEmitter : public ViewEventEmitter {
|
||||
public:
|
||||
using ViewEventEmitter::ViewEventEmitter;
|
||||
|
||||
struct OnLinkPress {
|
||||
std::string url;
|
||||
std::string sourceType;
|
||||
};
|
||||
|
||||
struct OnLinkLongPress {
|
||||
std::string url;
|
||||
};
|
||||
|
||||
struct OnImagePress {
|
||||
std::string url;
|
||||
std::string altText;
|
||||
};
|
||||
|
||||
struct OnTaskListItemPress {
|
||||
int index;
|
||||
bool checked;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
struct OnCopyPress {
|
||||
std::string code;
|
||||
std::string language;
|
||||
};
|
||||
|
||||
struct OnCodeBlockPress {
|
||||
std::string code;
|
||||
std::string language;
|
||||
};
|
||||
|
||||
struct OnLatexError {
|
||||
std::string source;
|
||||
std::string message;
|
||||
bool displayMode;
|
||||
};
|
||||
|
||||
struct OnLinkContextMenuItemPress {
|
||||
std::string url;
|
||||
std::string pattern;
|
||||
std::string itemText;
|
||||
};
|
||||
|
||||
struct OnContextMenuItemPress {
|
||||
std::string itemText;
|
||||
std::string selectedText;
|
||||
int selectionStart;
|
||||
int selectionEnd;
|
||||
};
|
||||
void onLinkPress(OnLinkPress value) const;
|
||||
|
||||
void onLinkLongPress(OnLinkLongPress value) const;
|
||||
|
||||
void onImagePress(OnImagePress value) const;
|
||||
|
||||
void onTaskListItemPress(OnTaskListItemPress value) const;
|
||||
|
||||
void onCopyPress(OnCopyPress value) const;
|
||||
|
||||
void onCodeBlockPress(OnCodeBlockPress value) const;
|
||||
|
||||
void onLatexError(OnLatexError value) const;
|
||||
|
||||
void onLinkContextMenuItemPress(OnLinkContextMenuItemPress value) const;
|
||||
|
||||
void onContextMenuItemPress(OnContextMenuItemPress value) const;
|
||||
};
|
||||
} // namespace facebook::react
|
||||
+510
@@ -0,0 +1,510 @@
|
||||
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GeneratePropsCpp.js
|
||||
*/
|
||||
|
||||
#include "Props.h"
|
||||
#include <react/renderer/core/PropsParserContext.h>
|
||||
#include <react/renderer/core/propsConversions.h>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
EnrichedMarkdownProps::EnrichedMarkdownProps(
|
||||
const PropsParserContext &context,
|
||||
const EnrichedMarkdownProps &sourceProps,
|
||||
const RawProps &rawProps): ViewProps(context, sourceProps, rawProps),
|
||||
|
||||
markdown(convertRawProp(context, rawProps, "markdown", sourceProps.markdown, {})),
|
||||
markdownStyle(convertRawProp(context, rawProps, "markdownStyle", sourceProps.markdownStyle, {})),
|
||||
enableImagePress(convertRawProp(context, rawProps, "enableImagePress", sourceProps.enableImagePress, {false})),
|
||||
enableTaskListItemToggle(convertRawProp(context, rawProps, "enableTaskListItemToggle", sourceProps.enableTaskListItemToggle, {true})),
|
||||
enableCodeBlockPress(convertRawProp(context, rawProps, "enableCodeBlockPress", sourceProps.enableCodeBlockPress, {false})),
|
||||
enableBlockContextMenu(convertRawProp(context, rawProps, "enableBlockContextMenu", sourceProps.enableBlockContextMenu, {true})),
|
||||
enableLinkPreview(convertRawProp(context, rawProps, "enableLinkPreview", sourceProps.enableLinkPreview, {true})),
|
||||
selectable(convertRawProp(context, rawProps, "selectable", sourceProps.selectable, {false})),
|
||||
selectionColor(convertRawProp(context, rawProps, "selectionColor", sourceProps.selectionColor, {})),
|
||||
selectionHandleColor(convertRawProp(context, rawProps, "selectionHandleColor", sourceProps.selectionHandleColor, {})),
|
||||
md4cFlags(convertRawProp(context, rawProps, "md4cFlags", sourceProps.md4cFlags, {})),
|
||||
isGFM(convertRawProp(context, rawProps, "isGFM", sourceProps.isGFM, {true})),
|
||||
allowFontScaling(convertRawProp(context, rawProps, "allowFontScaling", sourceProps.allowFontScaling, {true})),
|
||||
maxFontSizeMultiplier(convertRawProp(context, rawProps, "maxFontSizeMultiplier", sourceProps.maxFontSizeMultiplier, {0.0})),
|
||||
allowTrailingMargin(convertRawProp(context, rawProps, "allowTrailingMargin", sourceProps.allowTrailingMargin, {false})),
|
||||
streamingAnimation(convertRawProp(context, rawProps, "streamingAnimation", sourceProps.streamingAnimation, {false})),
|
||||
streamingConfig(convertRawProp(context, rawProps, "streamingConfig", sourceProps.streamingConfig, {})),
|
||||
spoilerOverlay(convertRawProp(context, rawProps, "spoilerOverlay", sourceProps.spoilerOverlay, {std::string{"particles"}})),
|
||||
contextMenuItems(convertRawProp(context, rawProps, "contextMenuItems", sourceProps.contextMenuItems, {})),
|
||||
imageRequestHeaders(convertRawProp(context, rawProps, "imageRequestHeaders", sourceProps.imageRequestHeaders, {})),
|
||||
linkPillContent(convertRawProp(context, rawProps, "linkPillContent", sourceProps.linkPillContent, {})),
|
||||
linkRecognition(convertRawProp(context, rawProps, "linkRecognition", sourceProps.linkRecognition, {})),
|
||||
linkContextMenuItems(convertRawProp(context, rawProps, "linkContextMenuItems", sourceProps.linkContextMenuItems, {})),
|
||||
selectionMenuConfig(convertRawProp(context, rawProps, "selectionMenuConfig", sourceProps.selectionMenuConfig, {})),
|
||||
accessibilityLabels(convertRawProp(context, rawProps, "accessibilityLabels", sourceProps.accessibilityLabels, {})),
|
||||
textBreakStrategy(convertRawProp(context, rawProps, "textBreakStrategy", sourceProps.textBreakStrategy, {std::string{"highQuality"}})),
|
||||
lineBreakStrategyIOS(convertRawProp(context, rawProps, "lineBreakStrategyIOS", sourceProps.lineBreakStrategyIOS, {std::string{"none"}})),
|
||||
writingDirection(convertRawProp(context, rawProps, "writingDirection", sourceProps.writingDirection, {std::string{"first-strong"}})),
|
||||
numberOfLines(convertRawProp(context, rawProps, "numberOfLines", sourceProps.numberOfLines, {0})),
|
||||
ellipsizeMode(convertRawProp(context, rawProps, "ellipsizeMode", sourceProps.ellipsizeMode, {std::string{"tail"}})) {}
|
||||
|
||||
#ifdef RN_SERIALIZABLE_STATE
|
||||
ComponentName EnrichedMarkdownProps::getDiffPropsImplementationTarget() const {
|
||||
return "EnrichedMarkdown";
|
||||
}
|
||||
|
||||
folly::dynamic EnrichedMarkdownProps::getDiffProps(
|
||||
const Props* prevProps) const {
|
||||
static const auto defaultProps = EnrichedMarkdownProps();
|
||||
const EnrichedMarkdownProps* oldProps = prevProps == nullptr
|
||||
? &defaultProps
|
||||
: static_cast<const EnrichedMarkdownProps*>(prevProps);
|
||||
if (this == oldProps) {
|
||||
return folly::dynamic::object();
|
||||
}
|
||||
folly::dynamic result = HostPlatformViewProps::getDiffProps(prevProps);
|
||||
|
||||
if (markdown != oldProps->markdown) {
|
||||
result["markdown"] = markdown;
|
||||
}
|
||||
|
||||
if (markdownStyle != oldProps->markdownStyle) {
|
||||
result["markdownStyle"] = toDynamic(markdownStyle);
|
||||
}
|
||||
|
||||
if (enableImagePress != oldProps->enableImagePress) {
|
||||
result["enableImagePress"] = enableImagePress;
|
||||
}
|
||||
|
||||
if (enableTaskListItemToggle != oldProps->enableTaskListItemToggle) {
|
||||
result["enableTaskListItemToggle"] = enableTaskListItemToggle;
|
||||
}
|
||||
|
||||
if (enableCodeBlockPress != oldProps->enableCodeBlockPress) {
|
||||
result["enableCodeBlockPress"] = enableCodeBlockPress;
|
||||
}
|
||||
|
||||
if (enableBlockContextMenu != oldProps->enableBlockContextMenu) {
|
||||
result["enableBlockContextMenu"] = enableBlockContextMenu;
|
||||
}
|
||||
|
||||
if (enableLinkPreview != oldProps->enableLinkPreview) {
|
||||
result["enableLinkPreview"] = enableLinkPreview;
|
||||
}
|
||||
|
||||
if (selectable != oldProps->selectable) {
|
||||
result["selectable"] = selectable;
|
||||
}
|
||||
|
||||
if (selectionColor != oldProps->selectionColor) {
|
||||
result["selectionColor"] = *selectionColor;
|
||||
}
|
||||
|
||||
if (selectionHandleColor != oldProps->selectionHandleColor) {
|
||||
result["selectionHandleColor"] = *selectionHandleColor;
|
||||
}
|
||||
|
||||
if (md4cFlags != oldProps->md4cFlags) {
|
||||
result["md4cFlags"] = toDynamic(md4cFlags);
|
||||
}
|
||||
|
||||
if (isGFM != oldProps->isGFM) {
|
||||
result["isGFM"] = isGFM;
|
||||
}
|
||||
|
||||
if (allowFontScaling != oldProps->allowFontScaling) {
|
||||
result["allowFontScaling"] = allowFontScaling;
|
||||
}
|
||||
|
||||
if ((maxFontSizeMultiplier != oldProps->maxFontSizeMultiplier) && !(std::isnan(maxFontSizeMultiplier) && std::isnan(oldProps->maxFontSizeMultiplier))) {
|
||||
result["maxFontSizeMultiplier"] = maxFontSizeMultiplier;
|
||||
}
|
||||
|
||||
if (allowTrailingMargin != oldProps->allowTrailingMargin) {
|
||||
result["allowTrailingMargin"] = allowTrailingMargin;
|
||||
}
|
||||
|
||||
if (streamingAnimation != oldProps->streamingAnimation) {
|
||||
result["streamingAnimation"] = streamingAnimation;
|
||||
}
|
||||
|
||||
if (streamingConfig != oldProps->streamingConfig) {
|
||||
result["streamingConfig"] = toDynamic(streamingConfig);
|
||||
}
|
||||
|
||||
if (spoilerOverlay != oldProps->spoilerOverlay) {
|
||||
result["spoilerOverlay"] = spoilerOverlay;
|
||||
}
|
||||
|
||||
if (contextMenuItems != oldProps->contextMenuItems) {
|
||||
result["contextMenuItems"] = toDynamic(contextMenuItems);
|
||||
}
|
||||
|
||||
if (imageRequestHeaders != oldProps->imageRequestHeaders) {
|
||||
result["imageRequestHeaders"] = toDynamic(imageRequestHeaders);
|
||||
}
|
||||
|
||||
if (linkPillContent != oldProps->linkPillContent) {
|
||||
result["linkPillContent"] = toDynamic(linkPillContent);
|
||||
}
|
||||
|
||||
if (linkRecognition != oldProps->linkRecognition) {
|
||||
result["linkRecognition"] = toDynamic(linkRecognition);
|
||||
}
|
||||
|
||||
if (linkContextMenuItems != oldProps->linkContextMenuItems) {
|
||||
result["linkContextMenuItems"] = toDynamic(linkContextMenuItems);
|
||||
}
|
||||
|
||||
if (selectionMenuConfig != oldProps->selectionMenuConfig) {
|
||||
result["selectionMenuConfig"] = toDynamic(selectionMenuConfig);
|
||||
}
|
||||
|
||||
if (accessibilityLabels != oldProps->accessibilityLabels) {
|
||||
result["accessibilityLabels"] = toDynamic(accessibilityLabels);
|
||||
}
|
||||
|
||||
if (textBreakStrategy != oldProps->textBreakStrategy) {
|
||||
result["textBreakStrategy"] = textBreakStrategy;
|
||||
}
|
||||
|
||||
if (lineBreakStrategyIOS != oldProps->lineBreakStrategyIOS) {
|
||||
result["lineBreakStrategyIOS"] = lineBreakStrategyIOS;
|
||||
}
|
||||
|
||||
if (writingDirection != oldProps->writingDirection) {
|
||||
result["writingDirection"] = writingDirection;
|
||||
}
|
||||
|
||||
if (numberOfLines != oldProps->numberOfLines) {
|
||||
result["numberOfLines"] = numberOfLines;
|
||||
}
|
||||
|
||||
if (ellipsizeMode != oldProps->ellipsizeMode) {
|
||||
result["ellipsizeMode"] = ellipsizeMode;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
EnrichedMarkdownTextInputProps::EnrichedMarkdownTextInputProps(
|
||||
const PropsParserContext &context,
|
||||
const EnrichedMarkdownTextInputProps &sourceProps,
|
||||
const RawProps &rawProps): ViewProps(context, sourceProps, rawProps),
|
||||
|
||||
defaultValue(convertRawProp(context, rawProps, "defaultValue", sourceProps.defaultValue, {})),
|
||||
placeholder(convertRawProp(context, rawProps, "placeholder", sourceProps.placeholder, {})),
|
||||
placeholderTextColor(convertRawProp(context, rawProps, "placeholderTextColor", sourceProps.placeholderTextColor, {})),
|
||||
editable(convertRawProp(context, rawProps, "editable", sourceProps.editable, {false})),
|
||||
autoFocus(convertRawProp(context, rawProps, "autoFocus", sourceProps.autoFocus, {false})),
|
||||
scrollEnabled(convertRawProp(context, rawProps, "scrollEnabled", sourceProps.scrollEnabled, {false})),
|
||||
markdownShortcuts(convertRawProp(context, rawProps, "markdownShortcuts", sourceProps.markdownShortcuts, {})),
|
||||
autoCapitalize(convertRawProp(context, rawProps, "autoCapitalize", sourceProps.autoCapitalize, {})),
|
||||
multiline(convertRawProp(context, rawProps, "multiline", sourceProps.multiline, {false})),
|
||||
cursorColor(convertRawProp(context, rawProps, "cursorColor", sourceProps.cursorColor, {})),
|
||||
selectionColor(convertRawProp(context, rawProps, "selectionColor", sourceProps.selectionColor, {})),
|
||||
markdownStyle(convertRawProp(context, rawProps, "markdownStyle", sourceProps.markdownStyle, {})),
|
||||
color(convertRawProp(context, rawProps, "color", sourceProps.color, {})),
|
||||
fontSize(convertRawProp(context, rawProps, "fontSize", sourceProps.fontSize, {0.0})),
|
||||
lineHeight(convertRawProp(context, rawProps, "lineHeight", sourceProps.lineHeight, {0.0})),
|
||||
fontFamily(convertRawProp(context, rawProps, "fontFamily", sourceProps.fontFamily, {})),
|
||||
fontWeight(convertRawProp(context, rawProps, "fontWeight", sourceProps.fontWeight, {})),
|
||||
isOnChangeMarkdownSet(convertRawProp(context, rawProps, "isOnChangeMarkdownSet", sourceProps.isOnChangeMarkdownSet, {false})),
|
||||
contextMenuItems(convertRawProp(context, rawProps, "contextMenuItems", sourceProps.contextMenuItems, {})),
|
||||
selectionMenuConfig(convertRawProp(context, rawProps, "selectionMenuConfig", sourceProps.selectionMenuConfig, {})),
|
||||
formatMenuConfig(convertRawProp(context, rawProps, "formatMenuConfig", sourceProps.formatMenuConfig, {})),
|
||||
linkRegex(convertRawProp(context, rawProps, "linkRegex", sourceProps.linkRegex, {})),
|
||||
mentionIndicators(convertRawProp(context, rawProps, "mentionIndicators", sourceProps.mentionIndicators, {})),
|
||||
writingDirection(convertRawProp(context, rawProps, "writingDirection", sourceProps.writingDirection, {std::string{"first-strong"}})) {}
|
||||
|
||||
#ifdef RN_SERIALIZABLE_STATE
|
||||
ComponentName EnrichedMarkdownTextInputProps::getDiffPropsImplementationTarget() const {
|
||||
return "EnrichedMarkdownTextInput";
|
||||
}
|
||||
|
||||
folly::dynamic EnrichedMarkdownTextInputProps::getDiffProps(
|
||||
const Props* prevProps) const {
|
||||
static const auto defaultProps = EnrichedMarkdownTextInputProps();
|
||||
const EnrichedMarkdownTextInputProps* oldProps = prevProps == nullptr
|
||||
? &defaultProps
|
||||
: static_cast<const EnrichedMarkdownTextInputProps*>(prevProps);
|
||||
if (this == oldProps) {
|
||||
return folly::dynamic::object();
|
||||
}
|
||||
folly::dynamic result = HostPlatformViewProps::getDiffProps(prevProps);
|
||||
|
||||
if (defaultValue != oldProps->defaultValue) {
|
||||
result["defaultValue"] = defaultValue;
|
||||
}
|
||||
|
||||
if (placeholder != oldProps->placeholder) {
|
||||
result["placeholder"] = placeholder;
|
||||
}
|
||||
|
||||
if (placeholderTextColor != oldProps->placeholderTextColor) {
|
||||
result["placeholderTextColor"] = *placeholderTextColor;
|
||||
}
|
||||
|
||||
if (editable != oldProps->editable) {
|
||||
result["editable"] = editable;
|
||||
}
|
||||
|
||||
if (autoFocus != oldProps->autoFocus) {
|
||||
result["autoFocus"] = autoFocus;
|
||||
}
|
||||
|
||||
if (scrollEnabled != oldProps->scrollEnabled) {
|
||||
result["scrollEnabled"] = scrollEnabled;
|
||||
}
|
||||
|
||||
if (markdownShortcuts != oldProps->markdownShortcuts) {
|
||||
result["markdownShortcuts"] = toDynamic(markdownShortcuts);
|
||||
}
|
||||
|
||||
if (autoCapitalize != oldProps->autoCapitalize) {
|
||||
result["autoCapitalize"] = autoCapitalize;
|
||||
}
|
||||
|
||||
if (multiline != oldProps->multiline) {
|
||||
result["multiline"] = multiline;
|
||||
}
|
||||
|
||||
if (cursorColor != oldProps->cursorColor) {
|
||||
result["cursorColor"] = *cursorColor;
|
||||
}
|
||||
|
||||
if (selectionColor != oldProps->selectionColor) {
|
||||
result["selectionColor"] = *selectionColor;
|
||||
}
|
||||
|
||||
if (markdownStyle != oldProps->markdownStyle) {
|
||||
result["markdownStyle"] = toDynamic(markdownStyle);
|
||||
}
|
||||
|
||||
if (color != oldProps->color) {
|
||||
result["color"] = *color;
|
||||
}
|
||||
|
||||
if ((fontSize != oldProps->fontSize) && !(std::isnan(fontSize) && std::isnan(oldProps->fontSize))) {
|
||||
result["fontSize"] = fontSize;
|
||||
}
|
||||
|
||||
if ((lineHeight != oldProps->lineHeight) && !(std::isnan(lineHeight) && std::isnan(oldProps->lineHeight))) {
|
||||
result["lineHeight"] = lineHeight;
|
||||
}
|
||||
|
||||
if (fontFamily != oldProps->fontFamily) {
|
||||
result["fontFamily"] = fontFamily;
|
||||
}
|
||||
|
||||
if (fontWeight != oldProps->fontWeight) {
|
||||
result["fontWeight"] = fontWeight;
|
||||
}
|
||||
|
||||
if (isOnChangeMarkdownSet != oldProps->isOnChangeMarkdownSet) {
|
||||
result["isOnChangeMarkdownSet"] = isOnChangeMarkdownSet;
|
||||
}
|
||||
|
||||
if (contextMenuItems != oldProps->contextMenuItems) {
|
||||
result["contextMenuItems"] = toDynamic(contextMenuItems);
|
||||
}
|
||||
|
||||
if (selectionMenuConfig != oldProps->selectionMenuConfig) {
|
||||
result["selectionMenuConfig"] = toDynamic(selectionMenuConfig);
|
||||
}
|
||||
|
||||
if (formatMenuConfig != oldProps->formatMenuConfig) {
|
||||
result["formatMenuConfig"] = toDynamic(formatMenuConfig);
|
||||
}
|
||||
|
||||
if (linkRegex != oldProps->linkRegex) {
|
||||
result["linkRegex"] = toDynamic(linkRegex);
|
||||
}
|
||||
|
||||
if (mentionIndicators != oldProps->mentionIndicators) {
|
||||
result["mentionIndicators"] = toDynamic(mentionIndicators);
|
||||
}
|
||||
|
||||
if (writingDirection != oldProps->writingDirection) {
|
||||
result["writingDirection"] = writingDirection;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
EnrichedMarkdownTextProps::EnrichedMarkdownTextProps(
|
||||
const PropsParserContext &context,
|
||||
const EnrichedMarkdownTextProps &sourceProps,
|
||||
const RawProps &rawProps): ViewProps(context, sourceProps, rawProps),
|
||||
|
||||
markdown(convertRawProp(context, rawProps, "markdown", sourceProps.markdown, {})),
|
||||
markdownStyle(convertRawProp(context, rawProps, "markdownStyle", sourceProps.markdownStyle, {})),
|
||||
enableImagePress(convertRawProp(context, rawProps, "enableImagePress", sourceProps.enableImagePress, {false})),
|
||||
enableTaskListItemToggle(convertRawProp(context, rawProps, "enableTaskListItemToggle", sourceProps.enableTaskListItemToggle, {true})),
|
||||
enableCodeBlockPress(convertRawProp(context, rawProps, "enableCodeBlockPress", sourceProps.enableCodeBlockPress, {false})),
|
||||
enableBlockContextMenu(convertRawProp(context, rawProps, "enableBlockContextMenu", sourceProps.enableBlockContextMenu, {true})),
|
||||
enableLinkPreview(convertRawProp(context, rawProps, "enableLinkPreview", sourceProps.enableLinkPreview, {true})),
|
||||
selectable(convertRawProp(context, rawProps, "selectable", sourceProps.selectable, {false})),
|
||||
selectionColor(convertRawProp(context, rawProps, "selectionColor", sourceProps.selectionColor, {})),
|
||||
selectionHandleColor(convertRawProp(context, rawProps, "selectionHandleColor", sourceProps.selectionHandleColor, {})),
|
||||
md4cFlags(convertRawProp(context, rawProps, "md4cFlags", sourceProps.md4cFlags, {})),
|
||||
isGFM(convertRawProp(context, rawProps, "isGFM", sourceProps.isGFM, {false})),
|
||||
allowFontScaling(convertRawProp(context, rawProps, "allowFontScaling", sourceProps.allowFontScaling, {true})),
|
||||
maxFontSizeMultiplier(convertRawProp(context, rawProps, "maxFontSizeMultiplier", sourceProps.maxFontSizeMultiplier, {0.0})),
|
||||
allowTrailingMargin(convertRawProp(context, rawProps, "allowTrailingMargin", sourceProps.allowTrailingMargin, {false})),
|
||||
streamingAnimation(convertRawProp(context, rawProps, "streamingAnimation", sourceProps.streamingAnimation, {false})),
|
||||
streamingConfig(convertRawProp(context, rawProps, "streamingConfig", sourceProps.streamingConfig, {})),
|
||||
spoilerOverlay(convertRawProp(context, rawProps, "spoilerOverlay", sourceProps.spoilerOverlay, {std::string{"particles"}})),
|
||||
contextMenuItems(convertRawProp(context, rawProps, "contextMenuItems", sourceProps.contextMenuItems, {})),
|
||||
imageRequestHeaders(convertRawProp(context, rawProps, "imageRequestHeaders", sourceProps.imageRequestHeaders, {})),
|
||||
linkPillContent(convertRawProp(context, rawProps, "linkPillContent", sourceProps.linkPillContent, {})),
|
||||
linkRecognition(convertRawProp(context, rawProps, "linkRecognition", sourceProps.linkRecognition, {})),
|
||||
linkContextMenuItems(convertRawProp(context, rawProps, "linkContextMenuItems", sourceProps.linkContextMenuItems, {})),
|
||||
selectionMenuConfig(convertRawProp(context, rawProps, "selectionMenuConfig", sourceProps.selectionMenuConfig, {})),
|
||||
accessibilityLabels(convertRawProp(context, rawProps, "accessibilityLabels", sourceProps.accessibilityLabels, {})),
|
||||
textBreakStrategy(convertRawProp(context, rawProps, "textBreakStrategy", sourceProps.textBreakStrategy, {std::string{"highQuality"}})),
|
||||
lineBreakStrategyIOS(convertRawProp(context, rawProps, "lineBreakStrategyIOS", sourceProps.lineBreakStrategyIOS, {std::string{"none"}})),
|
||||
writingDirection(convertRawProp(context, rawProps, "writingDirection", sourceProps.writingDirection, {std::string{"first-strong"}})),
|
||||
numberOfLines(convertRawProp(context, rawProps, "numberOfLines", sourceProps.numberOfLines, {0})),
|
||||
ellipsizeMode(convertRawProp(context, rawProps, "ellipsizeMode", sourceProps.ellipsizeMode, {std::string{"tail"}})) {}
|
||||
|
||||
#ifdef RN_SERIALIZABLE_STATE
|
||||
ComponentName EnrichedMarkdownTextProps::getDiffPropsImplementationTarget() const {
|
||||
return "EnrichedMarkdownText";
|
||||
}
|
||||
|
||||
folly::dynamic EnrichedMarkdownTextProps::getDiffProps(
|
||||
const Props* prevProps) const {
|
||||
static const auto defaultProps = EnrichedMarkdownTextProps();
|
||||
const EnrichedMarkdownTextProps* oldProps = prevProps == nullptr
|
||||
? &defaultProps
|
||||
: static_cast<const EnrichedMarkdownTextProps*>(prevProps);
|
||||
if (this == oldProps) {
|
||||
return folly::dynamic::object();
|
||||
}
|
||||
folly::dynamic result = HostPlatformViewProps::getDiffProps(prevProps);
|
||||
|
||||
if (markdown != oldProps->markdown) {
|
||||
result["markdown"] = markdown;
|
||||
}
|
||||
|
||||
if (markdownStyle != oldProps->markdownStyle) {
|
||||
result["markdownStyle"] = toDynamic(markdownStyle);
|
||||
}
|
||||
|
||||
if (enableImagePress != oldProps->enableImagePress) {
|
||||
result["enableImagePress"] = enableImagePress;
|
||||
}
|
||||
|
||||
if (enableTaskListItemToggle != oldProps->enableTaskListItemToggle) {
|
||||
result["enableTaskListItemToggle"] = enableTaskListItemToggle;
|
||||
}
|
||||
|
||||
if (enableCodeBlockPress != oldProps->enableCodeBlockPress) {
|
||||
result["enableCodeBlockPress"] = enableCodeBlockPress;
|
||||
}
|
||||
|
||||
if (enableBlockContextMenu != oldProps->enableBlockContextMenu) {
|
||||
result["enableBlockContextMenu"] = enableBlockContextMenu;
|
||||
}
|
||||
|
||||
if (enableLinkPreview != oldProps->enableLinkPreview) {
|
||||
result["enableLinkPreview"] = enableLinkPreview;
|
||||
}
|
||||
|
||||
if (selectable != oldProps->selectable) {
|
||||
result["selectable"] = selectable;
|
||||
}
|
||||
|
||||
if (selectionColor != oldProps->selectionColor) {
|
||||
result["selectionColor"] = *selectionColor;
|
||||
}
|
||||
|
||||
if (selectionHandleColor != oldProps->selectionHandleColor) {
|
||||
result["selectionHandleColor"] = *selectionHandleColor;
|
||||
}
|
||||
|
||||
if (md4cFlags != oldProps->md4cFlags) {
|
||||
result["md4cFlags"] = toDynamic(md4cFlags);
|
||||
}
|
||||
|
||||
if (isGFM != oldProps->isGFM) {
|
||||
result["isGFM"] = isGFM;
|
||||
}
|
||||
|
||||
if (allowFontScaling != oldProps->allowFontScaling) {
|
||||
result["allowFontScaling"] = allowFontScaling;
|
||||
}
|
||||
|
||||
if ((maxFontSizeMultiplier != oldProps->maxFontSizeMultiplier) && !(std::isnan(maxFontSizeMultiplier) && std::isnan(oldProps->maxFontSizeMultiplier))) {
|
||||
result["maxFontSizeMultiplier"] = maxFontSizeMultiplier;
|
||||
}
|
||||
|
||||
if (allowTrailingMargin != oldProps->allowTrailingMargin) {
|
||||
result["allowTrailingMargin"] = allowTrailingMargin;
|
||||
}
|
||||
|
||||
if (streamingAnimation != oldProps->streamingAnimation) {
|
||||
result["streamingAnimation"] = streamingAnimation;
|
||||
}
|
||||
|
||||
if (streamingConfig != oldProps->streamingConfig) {
|
||||
result["streamingConfig"] = toDynamic(streamingConfig);
|
||||
}
|
||||
|
||||
if (spoilerOverlay != oldProps->spoilerOverlay) {
|
||||
result["spoilerOverlay"] = spoilerOverlay;
|
||||
}
|
||||
|
||||
if (contextMenuItems != oldProps->contextMenuItems) {
|
||||
result["contextMenuItems"] = toDynamic(contextMenuItems);
|
||||
}
|
||||
|
||||
if (imageRequestHeaders != oldProps->imageRequestHeaders) {
|
||||
result["imageRequestHeaders"] = toDynamic(imageRequestHeaders);
|
||||
}
|
||||
|
||||
if (linkPillContent != oldProps->linkPillContent) {
|
||||
result["linkPillContent"] = toDynamic(linkPillContent);
|
||||
}
|
||||
|
||||
if (linkRecognition != oldProps->linkRecognition) {
|
||||
result["linkRecognition"] = toDynamic(linkRecognition);
|
||||
}
|
||||
|
||||
if (linkContextMenuItems != oldProps->linkContextMenuItems) {
|
||||
result["linkContextMenuItems"] = toDynamic(linkContextMenuItems);
|
||||
}
|
||||
|
||||
if (selectionMenuConfig != oldProps->selectionMenuConfig) {
|
||||
result["selectionMenuConfig"] = toDynamic(selectionMenuConfig);
|
||||
}
|
||||
|
||||
if (accessibilityLabels != oldProps->accessibilityLabels) {
|
||||
result["accessibilityLabels"] = toDynamic(accessibilityLabels);
|
||||
}
|
||||
|
||||
if (textBreakStrategy != oldProps->textBreakStrategy) {
|
||||
result["textBreakStrategy"] = textBreakStrategy;
|
||||
}
|
||||
|
||||
if (lineBreakStrategyIOS != oldProps->lineBreakStrategyIOS) {
|
||||
result["lineBreakStrategyIOS"] = lineBreakStrategyIOS;
|
||||
}
|
||||
|
||||
if (writingDirection != oldProps->writingDirection) {
|
||||
result["writingDirection"] = writingDirection;
|
||||
}
|
||||
|
||||
if (numberOfLines != oldProps->numberOfLines) {
|
||||
result["numberOfLines"] = numberOfLines;
|
||||
}
|
||||
|
||||
if (ellipsizeMode != oldProps->ellipsizeMode) {
|
||||
result["ellipsizeMode"] = ellipsizeMode;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace facebook::react
|
||||
+8153
File diff suppressed because it is too large
Load Diff
+17
@@ -0,0 +1,17 @@
|
||||
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateShadowNodeCpp.js
|
||||
*/
|
||||
|
||||
#include "ShadowNodes.h"
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
|
||||
|
||||
} // namespace facebook::react
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateShadowNodeH.js
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "EventEmitters.h"
|
||||
#include "Props.h"
|
||||
#include "States.h"
|
||||
#include <react/renderer/components/view/ConcreteViewShadowNode.h>
|
||||
#include <jsi/jsi.h>
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
|
||||
|
||||
} // namespace facebook::react
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateStateCpp.js
|
||||
*/
|
||||
#include "States.h"
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
|
||||
|
||||
} // namespace facebook::react
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
|
||||
*
|
||||
* Do not edit this file as changes may cause incorrect behavior and will be lost
|
||||
* once the code is regenerated.
|
||||
*
|
||||
* @generated by codegen project: GenerateStateH.js
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <react/renderer/core/StateData.h>
|
||||
#ifdef RN_SERIALIZABLE_STATE
|
||||
#include <folly/dynamic.h>
|
||||
#endif
|
||||
|
||||
namespace facebook::react {
|
||||
|
||||
|
||||
|
||||
} // namespace facebook::react
|
||||
@@ -0,0 +1,5 @@
|
||||
EnrichedMarkdown_kotlinVersion=2.0.21
|
||||
EnrichedMarkdown_minSdkVersion=24
|
||||
EnrichedMarkdown_targetSdkVersion=34
|
||||
EnrichedMarkdown_compileSdkVersion=35
|
||||
EnrichedMarkdown_ndkVersion=27.1.12297006
|
||||
@@ -0,0 +1,2 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
</manifest>
|
||||
@@ -0,0 +1,326 @@
|
||||
# Baseline Profile for react-native-enriched-markdown
|
||||
# These classes will be AOT compiled during app install
|
||||
# to improve cold start performance.
|
||||
|
||||
# Core View and Rendering
|
||||
Lcom/swmansion/enriched/markdown/EnrichedMarkdown;
|
||||
Lcom/swmansion/enriched/markdown/EnrichedMarkdown$DirtyFlag;
|
||||
Lcom/swmansion/enriched/markdown/EnrichedMarkdownInternalText;
|
||||
Lcom/swmansion/enriched/markdown/EnrichedMarkdownManager;
|
||||
Lcom/swmansion/enriched/markdown/EnrichedMarkdownText;
|
||||
Lcom/swmansion/enriched/markdown/EnrichedMarkdownTextLayoutManager;
|
||||
Lcom/swmansion/enriched/markdown/EnrichedMarkdownTextManager;
|
||||
Lcom/swmansion/enriched/markdown/EnrichedMarkdownTextPackage;
|
||||
Lcom/swmansion/enriched/markdown/MeasurementStore;
|
||||
Lcom/swmansion/enriched/markdown/MeasurementStore$FontScalingSettings;
|
||||
Lcom/swmansion/enriched/markdown/MeasurementStore$MeasurementParams;
|
||||
Lcom/swmansion/enriched/markdown/MeasurementStore$PaintParams;
|
||||
|
||||
# Accessibility
|
||||
Lcom/swmansion/enriched/markdown/accessibility/AccessibilityLabels;
|
||||
Lcom/swmansion/enriched/markdown/accessibility/AccessibleMarkdownTextView;
|
||||
Lcom/swmansion/enriched/markdown/accessibility/MarkdownAccessibilityHelper;
|
||||
Lcom/swmansion/enriched/markdown/accessibility/MarkdownAccessibilityHelper$AccessibilityItem;
|
||||
Lcom/swmansion/enriched/markdown/accessibility/MarkdownAccessibilityHelper$ListItemInfo;
|
||||
Lcom/swmansion/enriched/markdown/accessibility/MarkdownAccessibilityHelper$SpanRange;
|
||||
Lcom/swmansion/enriched/markdown/accessibility/MarkdownAccessibilityHelperKt;
|
||||
|
||||
# Events
|
||||
Lcom/swmansion/enriched/markdown/events/ContextMenuItemPressEvent;
|
||||
Lcom/swmansion/enriched/markdown/events/LinkLongPressEvent;
|
||||
Lcom/swmansion/enriched/markdown/events/LinkPressEvent;
|
||||
Lcom/swmansion/enriched/markdown/events/TaskListItemPressEvent;
|
||||
|
||||
# Input - Core
|
||||
Lcom/swmansion/enriched/markdown/input/EnrichedMarkdownTextInputManager;
|
||||
Lcom/swmansion/enriched/markdown/input/EnrichedMarkdownTextInputView;
|
||||
Lcom/swmansion/enriched/markdown/input/EnrichedMarkdownTextInputView$MentionCandidate;
|
||||
Lcom/swmansion/enriched/markdown/input/EnrichedMarkdownTextInputViewKt;
|
||||
|
||||
# Input - Autolink
|
||||
Lcom/swmansion/enriched/markdown/input/autolink/AutoDetectedLinkColorSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/autolink/AutoDetectedLinkMarkerSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/autolink/AutoDetectedLinkUnderlineSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/autolink/AutoLinkDetector;
|
||||
Lcom/swmansion/enriched/markdown/input/autolink/AutoLinkDetectorKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/common/LinkRegexConfig;
|
||||
|
||||
# Input - Detection
|
||||
Lcom/swmansion/enriched/markdown/input/detection/DetectorPipeline;
|
||||
Lcom/swmansion/enriched/markdown/input/detection/TextDetector;
|
||||
Lcom/swmansion/enriched/markdown/input/detection/WordResult;
|
||||
Lcom/swmansion/enriched/markdown/input/detection/WordsUtils;
|
||||
|
||||
# Input - Editing
|
||||
Lcom/swmansion/enriched/markdown/input/editing/InputConnectionWrapper;
|
||||
Lcom/swmansion/enriched/markdown/input/editing/MarkdownEditableFactory;
|
||||
Lcom/swmansion/enriched/markdown/input/editing/MarkdownTextWatcher;
|
||||
|
||||
# Input - Events
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnCaretRectChangeEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnChangeMentionEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnChangeMarkdownEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnChangeSelectionEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnChangeStateEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnChangeTextEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnContextMenuItemPressEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnEndMentionEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnInputBlurEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnInputFocusEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnLinkDetectedEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnRequestCaretRectResultEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnRequestMarkdownResultEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/events/OnStartMentionEvent;
|
||||
|
||||
# Input - Formatting
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/FormattingStore;
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/FormattingStore$EditOverlap;
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/InputFormatter;
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/InputParser;
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/InputRemend;
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/InputRemend$DelimiterPair;
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/MarkdownSerializer;
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/MarkdownSerializer$BoundaryEvent;
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/MarkdownSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/MarkdownSpan$SpanDescriptor;
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/ParseResult;
|
||||
Lcom/swmansion/enriched/markdown/input/formatting/ParseResult$ActiveStyle;
|
||||
|
||||
# Input - Layout
|
||||
Lcom/swmansion/enriched/markdown/input/layout/InputEventEmitter;
|
||||
Lcom/swmansion/enriched/markdown/input/layout/InputLayoutManager;
|
||||
Lcom/swmansion/enriched/markdown/input/layout/InputMeasurementStore;
|
||||
Lcom/swmansion/enriched/markdown/input/layout/InputMeasurementStore$MeasurementParams;
|
||||
Lcom/swmansion/enriched/markdown/input/layout/InputMeasurementStore$PaintParams;
|
||||
|
||||
# Input - Model
|
||||
Lcom/swmansion/enriched/markdown/input/model/CaretRect;
|
||||
Lcom/swmansion/enriched/markdown/input/model/FormattingRange;
|
||||
Lcom/swmansion/enriched/markdown/input/model/InputFormatterStyle;
|
||||
Lcom/swmansion/enriched/markdown/input/model/InputLinkVariantStyle;
|
||||
Lcom/swmansion/enriched/markdown/input/model/StyleType;
|
||||
|
||||
# Input - Styles
|
||||
Lcom/swmansion/enriched/markdown/input/styles/BoldStyleHandler;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/ItalicStyleHandler;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/LinkStyleHandler;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownBoldColorSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownBoldSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownItalicColorSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownItalicSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownLinkBackgroundColorSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownLinkColorSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownLinkColorSpan$ResolvedLinkStyle;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownLinkUnderlineSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownSpoilerBackgroundSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownSpoilerColorSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownStrikethroughSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/MarkdownUnderlineSpan;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/SpoilerStyleHandler;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/StrikethroughStyleHandler;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/StyleHandler;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/StyleMergingConfig;
|
||||
Lcom/swmansion/enriched/markdown/input/styles/UnderlineStyleHandler;
|
||||
|
||||
# Input - Toolbar
|
||||
Lcom/swmansion/enriched/markdown/input/toolbar/FormatMenuConfig;
|
||||
Lcom/swmansion/enriched/markdown/input/toolbar/InputContextMenu;
|
||||
Lcom/swmansion/enriched/markdown/input/toolbar/InputSelectionMenuConfig;
|
||||
|
||||
# Parser
|
||||
Lcom/swmansion/enriched/markdown/parser/Md4cFlags;
|
||||
Lcom/swmansion/enriched/markdown/parser/MarkdownASTNode;
|
||||
Lcom/swmansion/enriched/markdown/parser/MarkdownASTNode$NodeType;
|
||||
Lcom/swmansion/enriched/markdown/parser/MarkdownASTNodeKt;
|
||||
Lcom/swmansion/enriched/markdown/parser/Parser;
|
||||
|
||||
# Renderer Classes
|
||||
Lcom/swmansion/enriched/markdown/renderer/BaselineShiftRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/BlockStyle;
|
||||
Lcom/swmansion/enriched/markdown/renderer/BlockStyleContext;
|
||||
Lcom/swmansion/enriched/markdown/renderer/BlockStyleEntry;
|
||||
Lcom/swmansion/enriched/markdown/renderer/BlockType;
|
||||
Lcom/swmansion/enriched/markdown/renderer/BlockType$ListType;
|
||||
Lcom/swmansion/enriched/markdown/renderer/BlockquoteRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/CodeBlockRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/CodeBlockRenderer$CodeBlockBoundaryPaddingSpan;
|
||||
Lcom/swmansion/enriched/markdown/renderer/CodeRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/EmphasisRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/HeadingRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/HighlightRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/ImageRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/LineBreakRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/LinkRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/ListContextManager;
|
||||
Lcom/swmansion/enriched/markdown/renderer/ListContextManager$ListEntryState;
|
||||
Lcom/swmansion/enriched/markdown/renderer/ListItemRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/ListRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/MathInlineRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/NodeRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/NodeRenderer$DeferredSpan;
|
||||
Lcom/swmansion/enriched/markdown/renderer/ParagraphRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/Renderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/RendererConfig;
|
||||
Lcom/swmansion/enriched/markdown/renderer/RendererFactory;
|
||||
Lcom/swmansion/enriched/markdown/renderer/SpanStyleCache;
|
||||
Lcom/swmansion/enriched/markdown/renderer/SpoilerRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/StrikethroughRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/StrongRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/SubscriptRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/SuperscriptRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/TextRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/ThematicBreakRenderer;
|
||||
Lcom/swmansion/enriched/markdown/renderer/UnderlineRenderer;
|
||||
|
||||
# Spans
|
||||
Lcom/swmansion/enriched/markdown/spans/BaselineShiftSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/BaselineShiftSpan$SpanType;
|
||||
Lcom/swmansion/enriched/markdown/spans/BaseListSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/BlockquoteSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/CodeBackgroundSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/CodeBlockSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/CodeSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/EmphasisSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/FadeInSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/HeadingSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/HighlightSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/ImageSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/ImageSpan$CacheKey;
|
||||
Lcom/swmansion/enriched/markdown/spans/ImageSpan$ScaledImageDrawable;
|
||||
Lcom/swmansion/enriched/markdown/spans/LineHeightSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/LinkSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/MarginBottomSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/MathInlinePlaceholderSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/MathInlineSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/MathMeasureRequest;
|
||||
Lcom/swmansion/enriched/markdown/spans/MathMetrics;
|
||||
Lcom/swmansion/enriched/markdown/spans/MathRenderMode;
|
||||
Lcom/swmansion/enriched/markdown/spans/OrderedListSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/SpoilerSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/StrikethroughSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/StrongSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/TaskListSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/TextSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/ThematicBreakSpan;
|
||||
Lcom/swmansion/enriched/markdown/spans/UnorderedListSpan;
|
||||
|
||||
# Spoiler
|
||||
Lcom/swmansion/enriched/markdown/spoiler/ParticleStrategy;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SegmentKey;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SegmentRect;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SolidStrategy;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SolidStrategy$SegmentState;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SpoilerAnimator;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SpoilerCapable;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SpoilerConstantsKt;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SpoilerDrawContext;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SpoilerDrawUtilsKt;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SpoilerOverlay;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SpoilerOverlayDrawer;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SpoilerParticleDrawable;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SpoilerParticleDrawable$DotType;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SpoilerStrategy;
|
||||
Lcom/swmansion/enriched/markdown/spoiler/SpoilerStrategyKt;
|
||||
|
||||
# Style Configuration
|
||||
Lcom/swmansion/enriched/markdown/styles/BaseBlockStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/BlockquoteStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/CodeBlockStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/CodeStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/EmphasisStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/HeadingStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/HighlightStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/ImageStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/InlineImageStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/InlineMathStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/LinkStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/LinkVariantEntry;
|
||||
Lcom/swmansion/enriched/markdown/styles/ListStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/MathStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/ParagraphStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/SpoilerStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/StrikethroughStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/SubscriptStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/SuperscriptStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/StrongStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/StyleConfig;
|
||||
Lcom/swmansion/enriched/markdown/styles/StyleParser;
|
||||
Lcom/swmansion/enriched/markdown/styles/TableStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/TaskListStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/TextAlignment;
|
||||
Lcom/swmansion/enriched/markdown/styles/ThematicBreakStyle;
|
||||
Lcom/swmansion/enriched/markdown/styles/UnderlineStyle;
|
||||
|
||||
# Utilities - Common
|
||||
Lcom/swmansion/enriched/markdown/utils/common/BreakStrategyUtils;
|
||||
Lcom/swmansion/enriched/markdown/utils/common/FeatureFlags;
|
||||
Lcom/swmansion/enriched/markdown/segments/MarkdownSegment;
|
||||
Lcom/swmansion/enriched/markdown/segments/MarkdownSegment$Math;
|
||||
Lcom/swmansion/enriched/markdown/segments/MarkdownSegment$Table;
|
||||
Lcom/swmansion/enriched/markdown/segments/MarkdownSegment$Text;
|
||||
Lcom/swmansion/enriched/markdown/segments/MarkdownSegmentKt;
|
||||
Lcom/swmansion/enriched/markdown/segments/MarkdownSegmentRenderer;
|
||||
Lcom/swmansion/enriched/markdown/utils/common/MarkdownViewManagerUtilsKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/common/MotionPreferencesKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/common/ReadableMapExtensionsKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/common/ReconciliationResult;
|
||||
Lcom/swmansion/enriched/markdown/segments/RenderedSegment;
|
||||
Lcom/swmansion/enriched/markdown/segments/RenderedSegment$Math;
|
||||
Lcom/swmansion/enriched/markdown/segments/RenderedSegment$Table;
|
||||
Lcom/swmansion/enriched/markdown/segments/RenderedSegment$Text;
|
||||
Lcom/swmansion/enriched/markdown/segments/SegmentReconciler;
|
||||
Lcom/swmansion/enriched/markdown/segments/SegmentSignature;
|
||||
Lcom/swmansion/enriched/markdown/utils/common/StreamingMarkdownFilter;
|
||||
Lcom/swmansion/enriched/markdown/utils/common/TableStreamingMode;
|
||||
Lcom/swmansion/enriched/markdown/utils/common/layout/RTLUtilsKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/common/serialization/MarkdownASTSerializer;
|
||||
|
||||
# Utilities - Input
|
||||
Lcom/swmansion/enriched/markdown/utils/input/AutoCapitalizeUtils;
|
||||
Lcom/swmansion/enriched/markdown/utils/input/BorderPropsApplicator;
|
||||
Lcom/swmansion/enriched/markdown/utils/input/MarkdownStyleParser;
|
||||
|
||||
# Utilities - Text
|
||||
Lcom/swmansion/enriched/markdown/utils/text/ImageCache;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/ImageDownloader;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/TailFadeInAnimator;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/conversion/HTMLGenerator;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/conversion/HTMLGenerator$CachedStyles;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/conversion/HTMLGenerator$GeneratorState;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/conversion/HTMLGenerator$ParagraphInfo;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/conversion/MarkdownExtractor;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/conversion/MarkdownExtractor$ExtractionState;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/conversion/MarkdownExtractor$HeadingAccumulator;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/extensions/ParagraphUtilsKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/extensions/SpannableExtensionsKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/extensions/TextPaintExtensionsKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/interaction/CheckboxTouchHelper;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/interaction/TaskListHitTestResult;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/interaction/TaskListTapUtils;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/interaction/TaskListToggleUtils;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/span/BlockSpacingKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/span/SpanFlagsKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/view/LinkEventsKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/view/LinkLongPressMovementMethod;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/view/SelectionActionModeKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/view/SelectionMenuConfig;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/view/TextSelectionColorsKt;
|
||||
Lcom/swmansion/enriched/markdown/utils/text/view/TextViewSetupKt;
|
||||
|
||||
# Views
|
||||
Lcom/swmansion/enriched/markdown/segments/BlockSegmentView;
|
||||
Lcom/swmansion/enriched/markdown/views/ContextMenuPopup;
|
||||
Lcom/swmansion/enriched/markdown/views/ContextMenuPopup$Builder;
|
||||
Lcom/swmansion/enriched/markdown/views/ContextMenuPopup$Icon;
|
||||
Lcom/swmansion/enriched/markdown/views/ContextMenuPopup$MenuItem;
|
||||
Lcom/swmansion/enriched/markdown/segments/MathContainerView;
|
||||
Lcom/swmansion/enriched/markdown/segments/TableContainerView;
|
||||
Lcom/swmansion/enriched/markdown/segments/TableContainerView$CellBackgroundView;
|
||||
Lcom/swmansion/enriched/markdown/segments/TableContainerView$CellTextView;
|
||||
Lcom/swmansion/enriched/markdown/segments/TableContainerView$GridContainerView;
|
||||
Lcom/swmansion/enriched/markdown/segments/TableContainerView$HeaderTypefaceSpan;
|
||||
Lcom/swmansion/enriched/markdown/segments/TableContainerView$TableCellData;
|
||||
|
||||
# Math (optional, from src/math source set)
|
||||
Lcom/swmansion/enriched/markdown/spans/MathMeasureHelper;
|
||||
Lcom/swmansion/enriched/markdown/segments/MathContainerView$RaTeXCanvasView;
|
||||
@@ -0,0 +1,476 @@
|
||||
#include "CodeBlockHighlighter.hpp"
|
||||
#include "CodeBlockLanguages.hpp"
|
||||
#include "MD4CParser.hpp"
|
||||
#include "TextLinkRecognizer.hpp"
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
using namespace Markdown;
|
||||
|
||||
#define ENRICHEDMARKDOWN_LOG_TAG "EnrichedMarkdownJNI"
|
||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, ENRICHEDMARKDOWN_LOG_TAG, __VA_ARGS__)
|
||||
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, ENRICHEDMARKDOWN_LOG_TAG, __VA_ARGS__)
|
||||
|
||||
// Helper function to convert C++ NodeType to Kotlin enum ordinal
|
||||
static jint nodeTypeToJavaOrdinal(NodeType type) {
|
||||
switch (type) {
|
||||
case NodeType::Document:
|
||||
return 0;
|
||||
case NodeType::Paragraph:
|
||||
return 1;
|
||||
case NodeType::Text:
|
||||
return 2;
|
||||
case NodeType::Link:
|
||||
return 3;
|
||||
case NodeType::Heading:
|
||||
return 4;
|
||||
case NodeType::LineBreak:
|
||||
return 5;
|
||||
case NodeType::Strong:
|
||||
return 6;
|
||||
case NodeType::Emphasis:
|
||||
return 7;
|
||||
case NodeType::Strikethrough:
|
||||
return 8;
|
||||
case NodeType::Underline:
|
||||
return 9;
|
||||
case NodeType::Code:
|
||||
return 10;
|
||||
case NodeType::Image:
|
||||
return 11;
|
||||
case NodeType::Blockquote:
|
||||
return 12;
|
||||
case NodeType::UnorderedList:
|
||||
return 13;
|
||||
case NodeType::OrderedList:
|
||||
return 14;
|
||||
case NodeType::ListItem:
|
||||
return 15;
|
||||
case NodeType::CodeBlock:
|
||||
return 16;
|
||||
case NodeType::ThematicBreak:
|
||||
return 17;
|
||||
case NodeType::Table:
|
||||
return 18;
|
||||
case NodeType::TableHead:
|
||||
return 19;
|
||||
case NodeType::TableBody:
|
||||
return 20;
|
||||
case NodeType::TableRow:
|
||||
return 21;
|
||||
case NodeType::TableHeaderCell:
|
||||
return 22;
|
||||
case NodeType::TableCell:
|
||||
return 23;
|
||||
case NodeType::LatexMathInline:
|
||||
return 24;
|
||||
case NodeType::LatexMathDisplay:
|
||||
return 25;
|
||||
case NodeType::Spoiler:
|
||||
return 26;
|
||||
case NodeType::Superscript:
|
||||
return 27;
|
||||
case NodeType::Subscript:
|
||||
return 28;
|
||||
case NodeType::Highlight:
|
||||
return 29;
|
||||
case NodeType::SoftBreak:
|
||||
return 30;
|
||||
case NodeType::BlankLine:
|
||||
return 31;
|
||||
case NodeType::Admonition:
|
||||
return 32;
|
||||
case NodeType::Video:
|
||||
return 33;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to create a Kotlin MarkdownASTNode object from C++ AST node
|
||||
static jobject createJavaNode(JNIEnv *env, std::shared_ptr<MarkdownASTNode> node) {
|
||||
if (!node) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Find the MarkdownASTNode class
|
||||
jclass nodeClass = env->FindClass("com/swmansion/enriched/markdown/parser/MarkdownASTNode");
|
||||
if (!nodeClass) {
|
||||
LOGE("Failed to find MarkdownASTNode class");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Find the NodeType enum class
|
||||
jclass nodeTypeClass = env->FindClass("com/swmansion/enriched/markdown/parser/MarkdownASTNode$NodeType");
|
||||
if (!nodeTypeClass) {
|
||||
LOGE("Failed to find NodeType enum class");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Get the enum values array
|
||||
jmethodID valuesMethod = env->GetStaticMethodID(
|
||||
nodeTypeClass, "values", "()[Lcom/swmansion/enriched/markdown/parser/MarkdownASTNode$NodeType;");
|
||||
if (!valuesMethod) {
|
||||
LOGE("Failed to find NodeType.values() method");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jobjectArray enumValues = (jobjectArray)env->CallStaticObjectMethod(nodeTypeClass, valuesMethod);
|
||||
if (!enumValues) {
|
||||
LOGE("Failed to get NodeType enum values");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Get the enum value for this node type
|
||||
jint ordinal = nodeTypeToJavaOrdinal(node->type);
|
||||
jobject nodeTypeEnum = env->GetObjectArrayElement(enumValues, ordinal);
|
||||
if (!nodeTypeEnum) {
|
||||
LOGE("Failed to get NodeType enum value at index %d", ordinal);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Create content string
|
||||
jstring contentStr = env->NewStringUTF(node->content.c_str());
|
||||
if (!contentStr && !node->content.empty()) {
|
||||
LOGE("Failed to create content string");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Create attributes HashMap
|
||||
jclass mapClass = env->FindClass("java/util/HashMap");
|
||||
jmethodID mapInit = env->GetMethodID(mapClass, "<init>", "(I)V");
|
||||
jmethodID mapPut = env->GetMethodID(mapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
|
||||
|
||||
jobject attributesMap = env->NewObject(mapClass, mapInit, static_cast<jint>(node->attributes.size()));
|
||||
|
||||
for (const auto &pair : node->attributes) {
|
||||
jstring key = env->NewStringUTF(pair.first.c_str());
|
||||
jstring value = env->NewStringUTF(pair.second.c_str());
|
||||
env->CallObjectMethod(attributesMap, mapPut, key, value);
|
||||
env->DeleteLocalRef(key);
|
||||
env->DeleteLocalRef(value);
|
||||
}
|
||||
|
||||
// Create children ArrayList
|
||||
jclass listClass = env->FindClass("java/util/ArrayList");
|
||||
jmethodID listInit = env->GetMethodID(listClass, "<init>", "(I)V");
|
||||
jmethodID listAdd = env->GetMethodID(listClass, "add", "(Ljava/lang/Object;)Z");
|
||||
|
||||
jobject childrenList = env->NewObject(listClass, listInit, static_cast<jint>(node->children.size()));
|
||||
|
||||
for (const auto &child : node->children) {
|
||||
jobject childObj = createJavaNode(env, child);
|
||||
if (childObj) {
|
||||
env->CallBooleanMethod(childrenList, listAdd, childObj);
|
||||
env->DeleteLocalRef(childObj);
|
||||
}
|
||||
}
|
||||
|
||||
// Find the MarkdownASTNode constructor
|
||||
// Constructor signature: (Lcom/swmansion/enriched/markdown/parser/MarkdownASTNode$NodeType;Ljava/lang/String;Ljava/util/Map;Ljava/util/List;)V
|
||||
jmethodID constructor = env->GetMethodID(nodeClass, "<init>",
|
||||
"(Lcom/swmansion/enriched/markdown/parser/MarkdownASTNode$NodeType;Ljava/"
|
||||
"lang/String;Ljava/util/Map;Ljava/util/List;)V");
|
||||
if (!constructor) {
|
||||
LOGE("Failed to find MarkdownASTNode constructor");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Create the Kotlin MarkdownASTNode object
|
||||
jobject javaNode = env->NewObject(nodeClass, constructor, nodeTypeEnum, contentStr, attributesMap, childrenList);
|
||||
|
||||
// Clean up local references
|
||||
env->DeleteLocalRef(nodeTypeClass);
|
||||
env->DeleteLocalRef(enumValues);
|
||||
env->DeleteLocalRef(nodeTypeEnum);
|
||||
if (contentStr)
|
||||
env->DeleteLocalRef(contentStr);
|
||||
env->DeleteLocalRef(attributesMap);
|
||||
env->DeleteLocalRef(childrenList);
|
||||
|
||||
return javaNode;
|
||||
}
|
||||
|
||||
// UTF-16 via NewString, not NewStringUTF: the matcher's offsets must count the same units
|
||||
// the core maps back to bytes, and modified UTF-8 cannot carry 4-byte sequences.
|
||||
static std::u16string toUtf16(std::string_view utf8) {
|
||||
std::u16string out;
|
||||
out.reserve(utf8.size());
|
||||
for (size_t i = 0; i < utf8.size();) {
|
||||
unsigned char lead = static_cast<unsigned char>(utf8[i]);
|
||||
size_t length = lead < 0x80 ? 1 : lead < 0xE0 ? 2 : lead < 0xF0 ? 3 : 4;
|
||||
if (i + length > utf8.size())
|
||||
break;
|
||||
uint32_t codePoint = length == 1 ? lead
|
||||
: length == 2 ? ((lead & 0x1Fu) << 6) | (utf8[i + 1] & 0x3Fu)
|
||||
: length == 3 ? ((lead & 0x0Fu) << 12) | ((utf8[i + 1] & 0x3Fu) << 6) | (utf8[i + 2] & 0x3Fu)
|
||||
: ((lead & 0x07u) << 18) | ((utf8[i + 1] & 0x3Fu) << 12) |
|
||||
((utf8[i + 2] & 0x3Fu) << 6) | (utf8[i + 3] & 0x3Fu);
|
||||
if (codePoint >= 0x10000) {
|
||||
codePoint -= 0x10000;
|
||||
out.push_back(static_cast<char16_t>(0xD800 + (codePoint >> 10)));
|
||||
out.push_back(static_cast<char16_t>(0xDC00 + (codePoint & 0x3FF)));
|
||||
} else {
|
||||
out.push_back(static_cast<char16_t>(codePoint));
|
||||
}
|
||||
i += length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static jobjectArray toJavaStrings(JNIEnv *env, const std::vector<std::string_view> &strings) {
|
||||
jclass stringClass = env->FindClass("java/lang/String");
|
||||
jobjectArray array = env->NewObjectArray(static_cast<jsize>(strings.size()), stringClass, nullptr);
|
||||
for (size_t i = 0; i < strings.size(); i++) {
|
||||
std::u16string utf16 = toUtf16(strings[i]);
|
||||
jstring value = env->NewString(reinterpret_cast<const jchar *>(utf16.data()), static_cast<jsize>(utf16.size()));
|
||||
env->SetObjectArrayElement(array, static_cast<jsize>(i), value);
|
||||
env->DeleteLocalRef(value);
|
||||
}
|
||||
env->DeleteLocalRef(stringClass);
|
||||
return array;
|
||||
}
|
||||
|
||||
// A host exception must not leak into later JNI calls; recognition is dropped for that call.
|
||||
static bool clearHostException(JNIEnv *env) {
|
||||
if (!env->ExceptionCheck())
|
||||
return false;
|
||||
env->ExceptionDescribe();
|
||||
env->ExceptionClear();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Host matchers for the core recognizer: one JNI round trip per kind per parse, into TextLinkMatching.
|
||||
// Capturing env is safe because the core invokes these synchronously, inside this native call.
|
||||
static Markdown::TextLinkMatchers makeTextLinkMatchers(JNIEnv *env, jobject textConfig, jobject codeConfig) {
|
||||
Markdown::TextLinkMatchers matchers;
|
||||
if (!textConfig && !codeConfig)
|
||||
return matchers;
|
||||
jclass matchingClass = env->FindClass("com/swmansion/enriched/markdown/parser/TextLinkMatching");
|
||||
if (!matchingClass) {
|
||||
clearHostException(env);
|
||||
return matchers;
|
||||
}
|
||||
const char *configSig = "com/swmansion/enriched/markdown/utils/common/LinkRegexConfig";
|
||||
|
||||
if (textConfig) {
|
||||
jmethodID method = env->GetStaticMethodID(matchingClass, "matchText",
|
||||
("([Ljava/lang/String;L" + std::string(configSig) + ";)[I").c_str());
|
||||
if (!method) {
|
||||
clearHostException(env);
|
||||
return matchers;
|
||||
}
|
||||
matchers.text = [env, matchingClass, method, textConfig](const std::vector<std::string_view> &runs) {
|
||||
std::vector<std::vector<Markdown::TextRange>> all(runs.size());
|
||||
jobjectArray javaRuns = toJavaStrings(env, runs);
|
||||
jintArray triples = (jintArray)env->CallStaticObjectMethod(matchingClass, method, javaRuns, textConfig);
|
||||
env->DeleteLocalRef(javaRuns);
|
||||
if (clearHostException(env))
|
||||
return all;
|
||||
if (triples) {
|
||||
jsize count = env->GetArrayLength(triples);
|
||||
jint *data = env->GetIntArrayElements(triples, nullptr);
|
||||
for (jsize i = 0; i + 2 < count; i += 3) {
|
||||
size_t run = static_cast<size_t>(data[i]);
|
||||
if (run < all.size())
|
||||
all[run].push_back({static_cast<size_t>(data[i + 1]), static_cast<size_t>(data[i + 2])});
|
||||
}
|
||||
env->ReleaseIntArrayElements(triples, data, JNI_ABORT);
|
||||
env->DeleteLocalRef(triples);
|
||||
}
|
||||
return all;
|
||||
};
|
||||
}
|
||||
|
||||
if (codeConfig) {
|
||||
jmethodID method = env->GetStaticMethodID(matchingClass, "matchWholeCode",
|
||||
("([Ljava/lang/String;L" + std::string(configSig) + ";)[Z").c_str());
|
||||
if (!method) {
|
||||
clearHostException(env);
|
||||
return matchers;
|
||||
}
|
||||
matchers.inlineCode = [env, matchingClass, method, codeConfig](const std::vector<std::string_view> &spans) {
|
||||
std::vector<uint8_t> matched(spans.size(), 0);
|
||||
jobjectArray javaSpans = toJavaStrings(env, spans);
|
||||
jbooleanArray flags = (jbooleanArray)env->CallStaticObjectMethod(matchingClass, method, javaSpans, codeConfig);
|
||||
env->DeleteLocalRef(javaSpans);
|
||||
if (clearHostException(env))
|
||||
return matched;
|
||||
if (flags) {
|
||||
jsize count = env->GetArrayLength(flags);
|
||||
jboolean *data = env->GetBooleanArrayElements(flags, nullptr);
|
||||
for (jsize i = 0; i < count && static_cast<size_t>(i) < matched.size(); i++)
|
||||
matched[i] = data[i] == JNI_TRUE ? 1 : 0;
|
||||
env->ReleaseBooleanArrayElements(flags, data, JNI_ABORT);
|
||||
env->DeleteLocalRef(flags);
|
||||
}
|
||||
return matched;
|
||||
};
|
||||
}
|
||||
return matchers;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
JNIEXPORT jobject JNICALL Java_com_swmansion_enriched_markdown_parser_Parser_nativeParseMarkdown(
|
||||
JNIEnv *env, jobject /* this */, jstring markdown, jobject flags, jboolean isGFM, jobject textLinkRegex,
|
||||
jobject inlineCodeLinkRegex) {
|
||||
if (!markdown) {
|
||||
LOGE("Markdown string is null");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const char *markdownStr = env->GetStringUTFChars(markdown, nullptr);
|
||||
if (!markdownStr) {
|
||||
LOGE("Failed to get UTF-8 chars from markdown string");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
try {
|
||||
// Extract flags from Kotlin Md4cFlags data class
|
||||
Md4cFlags md4cFlags;
|
||||
if (flags) {
|
||||
jclass flagsClass = env->GetObjectClass(flags);
|
||||
if (flagsClass) {
|
||||
jfieldID underlineField = env->GetFieldID(flagsClass, "underline", "Z");
|
||||
if (underlineField) {
|
||||
md4cFlags.underline = env->GetBooleanField(flags, underlineField) == JNI_TRUE;
|
||||
}
|
||||
jfieldID latexMathField = env->GetFieldID(flagsClass, "latexMath", "Z");
|
||||
if (latexMathField) {
|
||||
md4cFlags.latexMath = env->GetBooleanField(flags, latexMathField) == JNI_TRUE;
|
||||
}
|
||||
jfieldID superscriptField = env->GetFieldID(flagsClass, "superscript", "Z");
|
||||
if (superscriptField) {
|
||||
md4cFlags.superscript = env->GetBooleanField(flags, superscriptField) == JNI_TRUE;
|
||||
}
|
||||
jfieldID subscriptField = env->GetFieldID(flagsClass, "subscript", "Z");
|
||||
if (subscriptField) {
|
||||
md4cFlags.subscript = env->GetBooleanField(flags, subscriptField) == JNI_TRUE;
|
||||
}
|
||||
jfieldID highlightField = env->GetFieldID(flagsClass, "highlight", "Z");
|
||||
if (highlightField) {
|
||||
md4cFlags.highlight = env->GetBooleanField(flags, highlightField) == JNI_TRUE;
|
||||
}
|
||||
jfieldID permissiveAutolinksField = env->GetFieldID(flagsClass, "permissiveAutolinks", "Z");
|
||||
if (permissiveAutolinksField) {
|
||||
md4cFlags.permissiveAutolinks = env->GetBooleanField(flags, permissiveAutolinksField) == JNI_TRUE;
|
||||
}
|
||||
jfieldID hardSoftBreaksField = env->GetFieldID(flagsClass, "hardSoftBreaks", "Z");
|
||||
if (hardSoftBreaksField) {
|
||||
md4cFlags.hardSoftBreaks = env->GetBooleanField(flags, hardSoftBreaksField) == JNI_TRUE;
|
||||
}
|
||||
jfieldID preserveBlankLinesField = env->GetFieldID(flagsClass, "preserveBlankLines", "Z");
|
||||
if (preserveBlankLinesField) {
|
||||
md4cFlags.preserveBlankLines = env->GetBooleanField(flags, preserveBlankLinesField) == JNI_TRUE;
|
||||
}
|
||||
jfieldID admonitionsField = env->GetFieldID(flagsClass, "admonitions", "Z");
|
||||
if (admonitionsField) {
|
||||
md4cFlags.admonitions = env->GetBooleanField(flags, admonitionsField) == JNI_TRUE;
|
||||
}
|
||||
env->DeleteLocalRef(flagsClass);
|
||||
}
|
||||
}
|
||||
|
||||
MD4CParser parser;
|
||||
auto ast = parser.parse(std::string(markdownStr), md4cFlags, isGFM == JNI_TRUE);
|
||||
|
||||
env->ReleaseStringUTFChars(markdown, markdownStr);
|
||||
|
||||
if (!ast) {
|
||||
LOGE("Parser returned null AST");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (textLinkRegex || inlineCodeLinkRegex) {
|
||||
Markdown::recognizeTextLinks(*ast, makeTextLinkMatchers(env, textLinkRegex, inlineCodeLinkRegex));
|
||||
}
|
||||
|
||||
// Convert C++ AST to Kotlin MarkdownASTNode object
|
||||
jobject javaNode = createJavaNode(env, ast);
|
||||
|
||||
if (!javaNode) {
|
||||
LOGE("Failed to create Java node from AST");
|
||||
}
|
||||
|
||||
return javaNode;
|
||||
} catch (const std::exception &e) {
|
||||
env->ReleaseStringUTFChars(markdown, markdownStr);
|
||||
LOGE("Exception during parsing: %s", e.what());
|
||||
return nullptr;
|
||||
} catch (...) {
|
||||
env->ReleaseStringUTFChars(markdown, markdownStr);
|
||||
LOGE("Unknown exception during parsing");
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT jstring JNICALL Java_com_swmansion_enriched_markdown_utils_common_CodeBlockNode_nativeDisplayLanguageName(
|
||||
JNIEnv *env, jobject /* this */, jstring language) {
|
||||
if (!language) {
|
||||
return nullptr;
|
||||
}
|
||||
const char *languageStr = env->GetStringUTFChars(language, nullptr);
|
||||
if (!languageStr) {
|
||||
return nullptr;
|
||||
}
|
||||
std::string display = displayNameForLanguage(languageStr);
|
||||
env->ReleaseStringUTFChars(language, languageStr);
|
||||
return env->NewStringUTF(display.c_str());
|
||||
}
|
||||
|
||||
// Returns highlight tokens as (start, end, type) int triplets with UTF-16
|
||||
// offsets, or null when highlighting is unavailable. See
|
||||
// cpp/highlight/CodeBlockHighlighter.hpp for the seam contract.
|
||||
JNIEXPORT jintArray JNICALL Java_com_swmansion_enriched_markdown_utils_common_CodeBlockHighlighter_nativeHighlightCode(
|
||||
JNIEnv *env, jobject /* this */, jstring code, jstring language) {
|
||||
if (!code) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const char *codeStr = env->GetStringUTFChars(code, nullptr);
|
||||
if (!codeStr) {
|
||||
return nullptr;
|
||||
}
|
||||
const char *languageStr = language ? env->GetStringUTFChars(language, nullptr) : nullptr;
|
||||
|
||||
std::vector<HighlightToken> tokens;
|
||||
try {
|
||||
tokens = highlightCode(codeStr, languageStr ? languageStr : "");
|
||||
} catch (const std::exception &e) {
|
||||
LOGE("Exception during highlighting: %s", e.what());
|
||||
tokens.clear();
|
||||
} catch (...) {
|
||||
LOGE("Unknown exception during highlighting");
|
||||
tokens.clear();
|
||||
}
|
||||
|
||||
env->ReleaseStringUTFChars(code, codeStr);
|
||||
if (languageStr) {
|
||||
env->ReleaseStringUTFChars(language, languageStr);
|
||||
}
|
||||
|
||||
if (tokens.empty()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::vector<jint> flat;
|
||||
flat.reserve(tokens.size() * 3);
|
||||
for (const auto &token : tokens) {
|
||||
flat.push_back(static_cast<jint>(token.start));
|
||||
flat.push_back(static_cast<jint>(token.end));
|
||||
flat.push_back(static_cast<jint>(token.type));
|
||||
}
|
||||
|
||||
jintArray result = env->NewIntArray(static_cast<jsize>(flat.size()));
|
||||
if (!result) {
|
||||
return nullptr;
|
||||
}
|
||||
env->SetIntArrayRegion(result, 0, static_cast<jsize>(flat.size()), flat.data());
|
||||
return result;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
+693
@@ -0,0 +1,693 @@
|
||||
package com.swmansion.enriched.markdown
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import com.facebook.react.bridge.Arguments
|
||||
import com.facebook.react.bridge.ReadableMap
|
||||
import com.facebook.react.uimanager.StateWrapper
|
||||
import com.swmansion.enriched.markdown.accessibility.AccessibilityLabels
|
||||
import com.swmansion.enriched.markdown.math.LatexErrorReporter
|
||||
import com.swmansion.enriched.markdown.parser.Md4cFlags
|
||||
import com.swmansion.enriched.markdown.parser.Parser
|
||||
import com.swmansion.enriched.markdown.segments.BlockquoteContainerView
|
||||
import com.swmansion.enriched.markdown.segments.CodeBlockContainerView
|
||||
import com.swmansion.enriched.markdown.segments.ContainerNodeView
|
||||
import com.swmansion.enriched.markdown.segments.DynamicBlockProps
|
||||
import com.swmansion.enriched.markdown.segments.MarkdownSegmentRenderer
|
||||
import com.swmansion.enriched.markdown.segments.RenderedSegment
|
||||
import com.swmansion.enriched.markdown.segments.SegmentViewConfig
|
||||
import com.swmansion.enriched.markdown.segments.SegmentViewCreators
|
||||
import com.swmansion.enriched.markdown.segments.SegmentViewFactory
|
||||
import com.swmansion.enriched.markdown.segments.TableContainerView
|
||||
import com.swmansion.enriched.markdown.segments.splitASTIntoSegments
|
||||
import com.swmansion.enriched.markdown.spoiler.SpoilerOverlay
|
||||
import com.swmansion.enriched.markdown.styles.LinkPillContent
|
||||
import com.swmansion.enriched.markdown.styles.StyleConfig
|
||||
import com.swmansion.enriched.markdown.utils.common.BreakStrategyUtils
|
||||
import com.swmansion.enriched.markdown.utils.common.CodeBlockStreamingMode
|
||||
import com.swmansion.enriched.markdown.utils.common.LinkRegexConfig
|
||||
import com.swmansion.enriched.markdown.utils.common.StreamingMarkdownFilter
|
||||
import com.swmansion.enriched.markdown.utils.common.TableStreamingMode
|
||||
import com.swmansion.enriched.markdown.utils.common.isReducedMotionEnabled
|
||||
import com.swmansion.enriched.markdown.utils.text.TailFadeInAnimator
|
||||
import com.swmansion.enriched.markdown.utils.text.view.ImagePressHost
|
||||
import com.swmansion.enriched.markdown.utils.text.view.SelectionMenuConfig
|
||||
import com.swmansion.enriched.markdown.utils.text.view.applySelectionColors
|
||||
import com.swmansion.enriched.markdown.utils.text.view.emitImagePressEvent
|
||||
import java.util.EnumSet
|
||||
import java.util.concurrent.ExecutorService
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
class EnrichedMarkdown(
|
||||
context: Context,
|
||||
) : ContainerNodeView(context),
|
||||
ImagePressHost {
|
||||
private enum class DirtyFlag {
|
||||
RECREATE_SEGMENTS,
|
||||
FORCE_HEIGHT,
|
||||
}
|
||||
|
||||
private val parser = Parser.shared
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
|
||||
private val mathContainerClass: Class<*>? by lazy { SegmentViewCreators.mathContainerClass() }
|
||||
private val videoContainerClass: Class<*>? by lazy { SegmentViewCreators.videoContainerClass() }
|
||||
|
||||
private var currentRenderId = 0L
|
||||
private val dirtyFlags = EnumSet.noneOf(DirtyFlag::class.java)
|
||||
var streamingAnimation: Boolean = false
|
||||
|
||||
// used to force a Yoga re-measure when a block image resolves its box height
|
||||
var stateWrapper: StateWrapper? = null
|
||||
private var forceHeightRecalculationCounter = 0
|
||||
|
||||
var tableStreamingMode: TableStreamingMode = TableStreamingMode.PROGRESSIVE
|
||||
var codeBlockStreamingMode: CodeBlockStreamingMode = CodeBlockStreamingMode.PROGRESSIVE
|
||||
private var renderPending: Boolean = false
|
||||
|
||||
var currentMarkdown: String = ""
|
||||
private set
|
||||
|
||||
var markdownStyle: StyleConfig? = null
|
||||
private set
|
||||
|
||||
private var markdownStyleMap: ReadableMap? = null
|
||||
private var lastKnownFontScale: Float = context.resources.configuration.fontScale
|
||||
|
||||
var md4cFlags: Md4cFlags = Md4cFlags.DEFAULT
|
||||
private set
|
||||
private var linkRegex: LinkRegexConfig? = null
|
||||
private var inlineCodeLinkRegex: LinkRegexConfig? = null
|
||||
private var isGFM: Boolean = true
|
||||
private var allowFontScaling: Boolean = true
|
||||
private var maxFontSizeMultiplier: Float = 0f
|
||||
private var imageRequestHeaders: Map<String, String> = emptyMap()
|
||||
private var linkPillContent: Map<String, LinkPillContent> = emptyMap()
|
||||
private var selectable: Boolean = true
|
||||
private var selectionColor: Int? = null
|
||||
private var selectionHandleColor: Int? = null
|
||||
private var selectionMenuConfig = SelectionMenuConfig()
|
||||
private var accessibilityLabels = AccessibilityLabels()
|
||||
private var textBreakStrategy: String = BreakStrategyUtils.DEFAULT_STRATEGY
|
||||
|
||||
private var onLinkPressCallback: ((String, String) -> Unit)? = null
|
||||
private var onLinkLongPressCallback: ((String) -> Unit)? = null
|
||||
private var onTaskListItemPressCallback: ((Int, Boolean, String) -> Unit)? = null
|
||||
private var onLatexErrorCallback: LatexErrorReporter? = null
|
||||
|
||||
private val reportedLatexErrors = HashSet<String>()
|
||||
|
||||
private val latexErrorReporter =
|
||||
LatexErrorReporter { source, message, displayMode ->
|
||||
val key = (if (displayMode) "B " else "I ") + source
|
||||
if (reportedLatexErrors.add(key)) {
|
||||
onLatexErrorCallback?.report(source, message, displayMode)
|
||||
}
|
||||
}
|
||||
private var contextMenuItemTexts: List<String> = emptyList()
|
||||
var onContextMenuItemPressCallback: ((itemText: String, selectedText: String, selectionStart: Int, selectionEnd: Int) -> Unit)? = null
|
||||
var spoilerOverlay: SpoilerOverlay = SpoilerOverlay.PARTICLES
|
||||
set(value) {
|
||||
if (field == value) return
|
||||
field = value
|
||||
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
|
||||
it.spoilerOverlay = value
|
||||
}
|
||||
}
|
||||
var enableTaskListItemToggle: Boolean = true
|
||||
set(value) {
|
||||
if (field == value) return
|
||||
field = value
|
||||
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
|
||||
it.enableTaskListItemToggle = value
|
||||
}
|
||||
}
|
||||
|
||||
private val dynamicProps = DynamicBlockProps()
|
||||
|
||||
var enableBlockContextMenu: Boolean
|
||||
get() = dynamicProps.enableBlockContextMenu
|
||||
set(value) {
|
||||
dynamicProps.enableBlockContextMenu = value
|
||||
}
|
||||
var enableCodeBlockPress: Boolean
|
||||
get() = dynamicProps.enableCodeBlockPress
|
||||
set(value) {
|
||||
dynamicProps.enableCodeBlockPress = value
|
||||
}
|
||||
|
||||
init {
|
||||
segmentViewFactory = RootFactory()
|
||||
}
|
||||
|
||||
fun setMarkdownContent(markdown: String) {
|
||||
if (currentMarkdown == markdown) return
|
||||
currentMarkdown = markdown
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
fun setMarkdownStyle(style: ReadableMap?) {
|
||||
markdownStyleMap = style
|
||||
val newConfig = style?.let { StyleConfig(it, context, allowFontScaling, maxFontSizeMultiplier) }
|
||||
newConfig?.imageRequestHeaders = imageRequestHeaders
|
||||
newConfig?.linkPillContent = linkPillContent
|
||||
if (markdownStyle == newConfig) return
|
||||
markdownStyle = newConfig
|
||||
dirtyFlags += DirtyFlag.RECREATE_SEGMENTS
|
||||
dirtyFlags += DirtyFlag.FORCE_HEIGHT
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
fun setImageRequestHeaders(headers: Map<String, String>) {
|
||||
if (imageRequestHeaders == headers) return
|
||||
imageRequestHeaders = headers
|
||||
markdownStyle?.imageRequestHeaders = headers
|
||||
dirtyFlags += DirtyFlag.RECREATE_SEGMENTS
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
fun setLinkPillContent(content: Map<String, LinkPillContent>) {
|
||||
if (linkPillContent == content) return
|
||||
linkPillContent = content
|
||||
markdownStyle?.linkPillContent = content
|
||||
// A label can change the pill's width and so the wrapped height.
|
||||
dirtyFlags += DirtyFlag.RECREATE_SEGMENTS
|
||||
dirtyFlags += DirtyFlag.FORCE_HEIGHT
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
fun commitProps() {
|
||||
MeasurementStore.updateStreamingTableMode(id, tableStreamingMode)
|
||||
MeasurementStore.updateStreamingCodeBlockMode(id, codeBlockStreamingMode)
|
||||
MeasurementStore.updateFontScalingSettings(id, allowFontScaling, maxFontSizeMultiplier)
|
||||
if (renderPending) {
|
||||
renderPending = false
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
if (!allowFontScaling) return
|
||||
val newFontScale = newConfig.fontScale
|
||||
if (newFontScale != lastKnownFontScale) {
|
||||
lastKnownFontScale = newFontScale
|
||||
recreateStyleConfig()
|
||||
dirtyFlags += DirtyFlag.RECREATE_SEGMENTS
|
||||
dirtyFlags += DirtyFlag.FORCE_HEIGHT
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
fun setLinkRegex(config: LinkRegexConfig?) {
|
||||
if (linkRegex == config) return
|
||||
linkRegex = config
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
fun setInlineCodeLinkRegex(config: LinkRegexConfig?) {
|
||||
if (inlineCodeLinkRegex == config) return
|
||||
inlineCodeLinkRegex = config
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
fun setMd4cFlags(flags: Md4cFlags) {
|
||||
if (md4cFlags == flags) return
|
||||
md4cFlags = flags
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
fun setIsGFM(value: Boolean) {
|
||||
if (isGFM == value) return
|
||||
isGFM = value
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
fun setAllowFontScaling(allow: Boolean) {
|
||||
if (allowFontScaling == allow) return
|
||||
allowFontScaling = allow
|
||||
MeasurementStore.updateFontScalingSettings(id, allowFontScaling, maxFontSizeMultiplier)
|
||||
recreateStyleConfig()
|
||||
dirtyFlags += DirtyFlag.RECREATE_SEGMENTS
|
||||
dirtyFlags += DirtyFlag.FORCE_HEIGHT
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
fun setMaxFontSizeMultiplier(multiplier: Float) {
|
||||
if (maxFontSizeMultiplier == multiplier) return
|
||||
maxFontSizeMultiplier = multiplier
|
||||
MeasurementStore.updateFontScalingSettings(id, allowFontScaling, maxFontSizeMultiplier)
|
||||
recreateStyleConfig()
|
||||
dirtyFlags += DirtyFlag.RECREATE_SEGMENTS
|
||||
dirtyFlags += DirtyFlag.FORCE_HEIGHT
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
fun setAllowTrailingMargin(allow: Boolean) {
|
||||
if (trailingMarginEnabled == allow) return
|
||||
trailingMarginEnabled = allow
|
||||
dirtyFlags += DirtyFlag.RECREATE_SEGMENTS
|
||||
dirtyFlags += DirtyFlag.FORCE_HEIGHT
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
fun setIsSelectable(value: Boolean) {
|
||||
if (selectable == value) return
|
||||
selectable = value
|
||||
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
|
||||
it.setIsSelectable(value)
|
||||
}
|
||||
}
|
||||
|
||||
fun setSelectionColor(color: Int?) {
|
||||
if (selectionColor == color) return
|
||||
selectionColor = color
|
||||
applySelectionColorsToSegments()
|
||||
}
|
||||
|
||||
fun setSelectionHandleColor(color: Int?) {
|
||||
if (selectionHandleColor == color) return
|
||||
selectionHandleColor = color
|
||||
applySelectionColorsToSegments()
|
||||
}
|
||||
|
||||
fun setTextBreakStrategy(strategy: String) {
|
||||
if (textBreakStrategy == strategy) return
|
||||
textBreakStrategy = strategy
|
||||
MeasurementStore.updateBreakStrategy(id, strategy)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
val resolved = BreakStrategyUtils.resolveBreakStrategy(strategy)
|
||||
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
|
||||
it.breakStrategy = resolved
|
||||
}
|
||||
}
|
||||
dirtyFlags += DirtyFlag.FORCE_HEIGHT
|
||||
renderPending = true
|
||||
}
|
||||
|
||||
private fun applySelectionColorsToSegments() {
|
||||
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
|
||||
it.applySelectionColors(selectionColor, selectionHandleColor)
|
||||
}
|
||||
}
|
||||
|
||||
fun setOnLinkPressCallback(callback: (String, String) -> Unit) {
|
||||
onLinkPressCallback = callback
|
||||
}
|
||||
|
||||
fun setOnLinkLongPressCallback(callback: (String) -> Unit) {
|
||||
onLinkLongPressCallback = callback
|
||||
}
|
||||
|
||||
fun setOnLatexErrorCallback(callback: LatexErrorReporter) {
|
||||
onLatexErrorCallback = callback
|
||||
}
|
||||
|
||||
override var imagePressEnabled: Boolean = false
|
||||
private set
|
||||
|
||||
override fun emitOnImagePress(
|
||||
url: String,
|
||||
altText: String,
|
||||
) {
|
||||
emitImagePressEvent(url, altText)
|
||||
}
|
||||
|
||||
fun setEnableImagePress(enabled: Boolean) {
|
||||
imagePressEnabled = enabled
|
||||
}
|
||||
|
||||
fun setOnTaskListItemPressCallback(callback: ((taskIndex: Int, checked: Boolean, itemText: String) -> Unit)?) {
|
||||
onTaskListItemPressCallback = callback
|
||||
}
|
||||
|
||||
fun setOnCopyPressCallback(callback: ((code: String, language: String) -> Unit)?) {
|
||||
dynamicProps.onCopyPress = callback
|
||||
}
|
||||
|
||||
fun setOnCodeBlockPressCallback(callback: ((code: String, language: String) -> Unit)?) {
|
||||
dynamicProps.onCodeBlockPress = callback
|
||||
}
|
||||
|
||||
fun setContextMenuItems(items: List<String>) {
|
||||
contextMenuItemTexts = items
|
||||
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
|
||||
it.setContextMenuItems(items, ::forwardContextMenuItemPress)
|
||||
}
|
||||
}
|
||||
|
||||
fun setSelectionMenuConfig(config: SelectionMenuConfig) {
|
||||
if (selectionMenuConfig == config) return
|
||||
selectionMenuConfig = config
|
||||
dynamicProps.copyLabel = config.copyLabel
|
||||
dynamicProps.copyAsMarkdownLabel = config.copyAsMarkdownLabel
|
||||
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
|
||||
it.selectionMenuConfig = config
|
||||
}
|
||||
}
|
||||
|
||||
fun setAccessibilityLabels(labels: AccessibilityLabels) {
|
||||
if (accessibilityLabels == labels) return
|
||||
accessibilityLabels = labels
|
||||
segmentViews.filterIsInstance<EnrichedMarkdownInternalText>().forEach {
|
||||
it.accessibilityLabels = labels
|
||||
}
|
||||
segmentViews.filterIsInstance<TableContainerView>().forEach {
|
||||
it.accessibilityLabels = labels
|
||||
}
|
||||
mathContainerClass?.let { mathClass ->
|
||||
segmentViews.filter { mathClass.isInstance(it) }.forEach { view ->
|
||||
runCatching {
|
||||
mathClass
|
||||
.getMethod("setAccessibilityLabels", AccessibilityLabels::class.java)
|
||||
.invoke(view, labels)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun forwardContextMenuItemPress(
|
||||
itemText: String,
|
||||
selectedText: String,
|
||||
selectionStart: Int,
|
||||
selectionEnd: Int,
|
||||
) {
|
||||
onContextMenuItemPressCallback?.invoke(itemText, selectedText, selectionStart, selectionEnd)
|
||||
}
|
||||
|
||||
private fun recreateStyleConfig() {
|
||||
markdownStyleMap?.let {
|
||||
markdownStyle =
|
||||
StyleConfig(it, context, allowFontScaling, maxFontSizeMultiplier).also { config ->
|
||||
config.imageRequestHeaders = imageRequestHeaders
|
||||
config.linkPillContent = linkPillContent
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun scheduleRenderIfNeeded() {
|
||||
if (currentMarkdown.isNotEmpty()) scheduleRender()
|
||||
}
|
||||
|
||||
private fun scheduleRender() {
|
||||
val style = markdownStyle ?: return
|
||||
val markdown = currentMarkdown.takeIf { it.isNotEmpty() } ?: return
|
||||
val isStreaming = streamingAnimation
|
||||
val tableMode = tableStreamingMode
|
||||
val codeBlockMode = codeBlockStreamingMode
|
||||
|
||||
val textLinkRegex = linkRegex
|
||||
val codeLinkRegex = inlineCodeLinkRegex
|
||||
val renderId = ++currentRenderId
|
||||
|
||||
dispatchMarkdownRender(segmentViews.isNotEmpty(), executor) {
|
||||
try {
|
||||
val filtered =
|
||||
if (isStreaming) {
|
||||
StreamingMarkdownFilter.renderableMarkdownForStreaming(markdown, tableMode, codeBlockMode)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val renderableMarkdown = filtered?.markdown ?: markdown
|
||||
val hasPendingCodeBlock = filtered?.endsInsideOpenCodeFence ?: false
|
||||
|
||||
if (renderableMarkdown.isEmpty()) {
|
||||
postToMain(renderId) { applyRenderedSegments(emptyList(), false) }
|
||||
return@dispatchMarkdownRender
|
||||
}
|
||||
|
||||
val ast =
|
||||
parser.parseMarkdown(renderableMarkdown, md4cFlags, isGFM, textLinkRegex, codeLinkRegex) ?: run {
|
||||
postToMain(renderId) { applyRenderedSegments(emptyList(), false) }
|
||||
return@dispatchMarkdownRender
|
||||
}
|
||||
|
||||
val segments = splitASTIntoSegments(ast)
|
||||
val renderedSegments =
|
||||
MarkdownSegmentRenderer.render(
|
||||
segments,
|
||||
style,
|
||||
context,
|
||||
onLinkPressCallback,
|
||||
onLinkLongPressCallback,
|
||||
onLatexError = latexErrorReporter,
|
||||
)
|
||||
|
||||
postToMain(renderId) { applyRenderedSegments(renderedSegments, hasPendingCodeBlock) }
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Render failed", e)
|
||||
postToMain(renderId) { applyRenderedSegments(emptyList(), false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Trailing code block whose closing fence hasn't streamed in yet, if any.
|
||||
private var pendingCodeBlockSegment: RenderedSegment.CodeBlock? = null
|
||||
|
||||
private fun applyRenderedSegments(
|
||||
renderedSegments: List<RenderedSegment>,
|
||||
hasPendingCodeBlock: Boolean,
|
||||
) {
|
||||
pendingCodeBlockSegment =
|
||||
if (hasPendingCodeBlock) renderedSegments.lastOrNull() as? RenderedSegment.CodeBlock else null
|
||||
|
||||
val reset = DirtyFlag.RECREATE_SEGMENTS in dirtyFlags
|
||||
val forceHeight = DirtyFlag.FORCE_HEIGHT in dirtyFlags
|
||||
dirtyFlags.clear()
|
||||
|
||||
val topologyChanged = applySegments(renderedSegments, reset)
|
||||
|
||||
// A just-closed block has unchanged content, so the reconciler reuses it
|
||||
// without an update; sync pending here to trigger its deferred highlight.
|
||||
segmentViews.forEachIndexed { index, view ->
|
||||
if (view is CodeBlockContainerView) {
|
||||
view.pending = pendingCodeBlockSegment != null && index == segmentViews.size - 1
|
||||
}
|
||||
}
|
||||
|
||||
if (width > 0) {
|
||||
val heightBefore = computeSegmentsTotalHeight()
|
||||
layoutSegments()
|
||||
val heightAfter = computeSegmentsTotalHeight()
|
||||
|
||||
if (forceHeight || topologyChanged || heightBefore != heightAfter) {
|
||||
MeasurementStore.invalidate(id)
|
||||
requestLayout()
|
||||
stateWrapper?.let {
|
||||
val state = Arguments.createMap()
|
||||
state.putInt("forceHeightRecalculationCounter", ++forceHeightRecalculationCounter)
|
||||
it.updateState(state)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun isMathContainerView(view: View): Boolean = mathContainerClass?.isInstance(view) == true
|
||||
|
||||
private fun isVideoContainerView(view: View): Boolean = videoContainerClass?.isInstance(view) == true
|
||||
|
||||
private fun segmentViewConfig(): SegmentViewConfig =
|
||||
SegmentViewConfig(
|
||||
context = context,
|
||||
style = markdownStyle!!,
|
||||
allowFontScaling = allowFontScaling,
|
||||
maxFontSizeMultiplier = maxFontSizeMultiplier,
|
||||
accessibilityLabels = accessibilityLabels,
|
||||
selectionMenuConfig = selectionMenuConfig,
|
||||
textBreakStrategy = textBreakStrategy,
|
||||
selectable = selectable,
|
||||
selectionColor = selectionColor,
|
||||
selectionHandleColor = selectionHandleColor,
|
||||
contextMenuItemTexts = contextMenuItemTexts,
|
||||
dynamicProps = dynamicProps,
|
||||
onLinkPress = onLinkPressCallback,
|
||||
onLinkLongPress = onLinkLongPressCallback,
|
||||
onTaskListItemPress = onTaskListItemPressCallback,
|
||||
onContextMenuItemPress = ::forwardContextMenuItemPress,
|
||||
onLatexError = latexErrorReporter,
|
||||
)
|
||||
|
||||
/**
|
||||
* Root factory: builds child views through the shared creators, then layers on
|
||||
* root-only concerns (spoiler overlay mode, task-list toggle, streaming tail /
|
||||
* fade-in animation, and the pending code block sync for the open trailing
|
||||
* fence).
|
||||
*/
|
||||
private inner class RootFactory : SegmentViewFactory {
|
||||
override fun matchesKind(
|
||||
view: View,
|
||||
segment: RenderedSegment,
|
||||
): Boolean =
|
||||
when (segment) {
|
||||
is RenderedSegment.Text -> view is EnrichedMarkdownInternalText
|
||||
is RenderedSegment.Table -> view is TableContainerView
|
||||
is RenderedSegment.Math -> isMathContainerView(view)
|
||||
is RenderedSegment.CodeBlock -> view is CodeBlockContainerView
|
||||
is RenderedSegment.Blockquote -> view is BlockquoteContainerView
|
||||
is RenderedSegment.Video -> isVideoContainerView(view)
|
||||
}
|
||||
|
||||
override fun createView(segment: RenderedSegment): View {
|
||||
val config = segmentViewConfig()
|
||||
return when (segment) {
|
||||
is RenderedSegment.Text -> {
|
||||
SegmentViewCreators.createTextView(segment, config).apply {
|
||||
spoilerOverlay = this@EnrichedMarkdown.spoilerOverlay
|
||||
enableTaskListItemToggle = this@EnrichedMarkdown.enableTaskListItemToggle
|
||||
}
|
||||
}
|
||||
|
||||
is RenderedSegment.Table -> {
|
||||
SegmentViewCreators.createTableView(segment, config)
|
||||
}
|
||||
|
||||
is RenderedSegment.Math -> {
|
||||
SegmentViewCreators.createMathView(segment, config)
|
||||
}
|
||||
|
||||
is RenderedSegment.CodeBlock -> {
|
||||
SegmentViewCreators.createCodeBlockView(segment, config).apply {
|
||||
pending = segment === pendingCodeBlockSegment
|
||||
}
|
||||
}
|
||||
|
||||
is RenderedSegment.Blockquote -> {
|
||||
SegmentViewCreators.createBlockquoteView(segment, config)
|
||||
}
|
||||
|
||||
is RenderedSegment.Video -> {
|
||||
SegmentViewCreators.createVideoView(segment, config)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun updateView(
|
||||
view: View,
|
||||
segment: RenderedSegment,
|
||||
) {
|
||||
when (segment) {
|
||||
is RenderedSegment.Text -> {
|
||||
val textView = view as EnrichedMarkdownInternalText
|
||||
val tailStart = textView.text?.length ?: 0
|
||||
SegmentViewCreators.updateTextView(textView, segment)
|
||||
animateTextViewTail(textView, tailStart)
|
||||
}
|
||||
|
||||
is RenderedSegment.Table -> {
|
||||
val tableView = view as TableContainerView
|
||||
val previousRowCount = tableView.rowCount
|
||||
tableView.applyTableNode(segment.node)
|
||||
if (streamingAnimation && !isReducedMotionEnabled(context)) {
|
||||
tableView.animateNewRows(previousRowCount, BLOCK_FADE_DURATION_MS)
|
||||
}
|
||||
}
|
||||
|
||||
is RenderedSegment.Math -> {
|
||||
SegmentViewCreators.updateMathView(view, segment)
|
||||
}
|
||||
|
||||
is RenderedSegment.CodeBlock -> {
|
||||
(view as CodeBlockContainerView).apply {
|
||||
pending = segment === pendingCodeBlockSegment
|
||||
applyCodeBlockNode(segment.node)
|
||||
}
|
||||
}
|
||||
|
||||
is RenderedSegment.Blockquote -> {
|
||||
(view as BlockquoteContainerView).applyBlockquoteNode(segment.node)
|
||||
}
|
||||
|
||||
is RenderedSegment.Video -> {
|
||||
SegmentViewCreators.updateVideoView(view, segment)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun animateNewView(
|
||||
view: View,
|
||||
segment: RenderedSegment,
|
||||
) {
|
||||
if (!streamingAnimation) return
|
||||
when (segment) {
|
||||
is RenderedSegment.Text -> animateTextViewTail(view as EnrichedMarkdownInternalText, 0)
|
||||
|
||||
is RenderedSegment.Table,
|
||||
is RenderedSegment.Math,
|
||||
is RenderedSegment.CodeBlock,
|
||||
is RenderedSegment.Blockquote,
|
||||
is RenderedSegment.Video,
|
||||
-> animateBlockViewFadeIn(view)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun animateTextViewTail(
|
||||
view: EnrichedMarkdownInternalText,
|
||||
tailStart: Int,
|
||||
) {
|
||||
if (!streamingAnimation) return
|
||||
val textLength = view.text?.length ?: 0
|
||||
if (textLength <= tailStart) return
|
||||
TailFadeInAnimator(view).animate(tailStart, textLength)
|
||||
}
|
||||
|
||||
private fun animateBlockViewFadeIn(view: View) {
|
||||
if (!streamingAnimation) return
|
||||
if (isReducedMotionEnabled(context)) return
|
||||
view.alpha = 0f
|
||||
view
|
||||
.animate()
|
||||
.alpha(1f)
|
||||
.setDuration(BLOCK_FADE_DURATION_MS)
|
||||
.start()
|
||||
}
|
||||
|
||||
private fun postToMain(
|
||||
renderId: Long,
|
||||
action: () -> Unit,
|
||||
) {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
if (renderId == currentRenderId) action()
|
||||
} else {
|
||||
mainHandler.post {
|
||||
if (renderId == currentRenderId) action()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onLayout(
|
||||
changed: Boolean,
|
||||
l: Int,
|
||||
t: Int,
|
||||
r: Int,
|
||||
b: Int,
|
||||
) {
|
||||
layoutSegments()
|
||||
}
|
||||
|
||||
fun onImageLayoutChanged() {
|
||||
if (width > 0) {
|
||||
layoutSegments()
|
||||
requestLayout()
|
||||
}
|
||||
MeasurementStore.invalidate(id)
|
||||
val wrapper = stateWrapper ?: return
|
||||
val state = Arguments.createMap()
|
||||
state.putInt("forceHeightRecalculationCounter", ++forceHeightRecalculationCounter)
|
||||
wrapper.updateState(state)
|
||||
}
|
||||
|
||||
fun cleanup() {
|
||||
executor.shutdownNow()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "EnrichedMarkdown"
|
||||
private const val BLOCK_FADE_DURATION_MS = 200L
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package com.swmansion.enriched.markdown
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.os.Build
|
||||
import android.text.Layout
|
||||
import android.util.AttributeSet
|
||||
import android.view.MotionEvent
|
||||
import com.swmansion.enriched.markdown.accessibility.AccessibilityLabels
|
||||
import com.swmansion.enriched.markdown.accessibility.AccessibleMarkdownTextView
|
||||
import com.swmansion.enriched.markdown.segments.BlockSegmentView
|
||||
import com.swmansion.enriched.markdown.spoiler.SpoilerCapable
|
||||
import com.swmansion.enriched.markdown.spoiler.SpoilerOverlay
|
||||
import com.swmansion.enriched.markdown.spoiler.SpoilerOverlayDrawer
|
||||
import com.swmansion.enriched.markdown.utils.text.interaction.CheckboxTouchHelper
|
||||
import com.swmansion.enriched.markdown.utils.text.view.LinkLongPressMovementMethod
|
||||
import com.swmansion.enriched.markdown.utils.text.view.SelectionMenuConfig
|
||||
import com.swmansion.enriched.markdown.utils.text.view.applySelectableState
|
||||
import com.swmansion.enriched.markdown.utils.text.view.cancelJSTouchForCheckboxTap
|
||||
import com.swmansion.enriched.markdown.utils.text.view.cancelJSTouchForLinkTap
|
||||
import com.swmansion.enriched.markdown.utils.text.view.createSelectionActionModeCallback
|
||||
import com.swmansion.enriched.markdown.utils.text.view.reallowParentInterceptIfLinkReleased
|
||||
import com.swmansion.enriched.markdown.utils.text.view.setupAsMarkdownTextView
|
||||
|
||||
class EnrichedMarkdownInternalText
|
||||
@JvmOverloads
|
||||
constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
defStyleAttr: Int = 0,
|
||||
) : AccessibleMarkdownTextView(context, attrs, defStyleAttr),
|
||||
BlockSegmentView,
|
||||
SpoilerCapable {
|
||||
var lastElementMarginBottom: Float = 0f
|
||||
|
||||
private val checkboxTouchHelper = CheckboxTouchHelper(this)
|
||||
|
||||
var onTaskListItemPressCallback: ((taskIndex: Int, checked: Boolean, itemText: String) -> Unit)?
|
||||
get() = checkboxTouchHelper.onCheckboxTap
|
||||
set(value) {
|
||||
checkboxTouchHelper.onCheckboxTap = value
|
||||
}
|
||||
|
||||
var enableTaskListItemToggle: Boolean
|
||||
get() = checkboxTouchHelper.isEnabled
|
||||
set(value) {
|
||||
checkboxTouchHelper.isEnabled = value
|
||||
}
|
||||
|
||||
override val segmentMarginBottom: Int get() = lastElementMarginBottom.toInt()
|
||||
|
||||
override var spoilerOverlayDrawer: SpoilerOverlayDrawer? = null
|
||||
private set
|
||||
var spoilerOverlay: SpoilerOverlay = SpoilerOverlay.PARTICLES
|
||||
private var contextMenuItemTexts: List<String> = emptyList()
|
||||
private var onContextMenuItemPress: ((itemText: String, selectedText: String, selectionStart: Int, selectionEnd: Int) -> Unit)? = null
|
||||
var selectionMenuConfig: SelectionMenuConfig = SelectionMenuConfig()
|
||||
var accessibilityLabels: AccessibilityLabels = AccessibilityLabels()
|
||||
set(value) {
|
||||
field = value
|
||||
accessibilityHelper.labels = value
|
||||
}
|
||||
|
||||
init {
|
||||
setupAsMarkdownTextView()
|
||||
customSelectionActionModeCallback =
|
||||
createSelectionActionModeCallback(
|
||||
this,
|
||||
getCustomItemTexts = { contextMenuItemTexts },
|
||||
getSelectionMenuConfig = { selectionMenuConfig },
|
||||
onCustomItemPress = { itemText, selectedText, start, end ->
|
||||
onContextMenuItemPress?.invoke(itemText, selectedText, start, end)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fun applyStyledText(styledText: CharSequence) {
|
||||
text = styledText
|
||||
|
||||
if (movementMethod !is LinkLongPressMovementMethod) {
|
||||
movementMethod = LinkLongPressMovementMethod.createInstance()
|
||||
}
|
||||
|
||||
spoilerOverlayDrawer = SpoilerOverlayDrawer.setupIfNeeded(this, styledText, spoilerOverlayDrawer, spoilerOverlay)
|
||||
accessibilityHelper.invalidateAccessibilityItems()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
spoilerOverlayDrawer?.draw(canvas)
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
spoilerOverlayDrawer?.stop()
|
||||
spoilerOverlayDrawer = null
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
fun setIsSelectable(selectable: Boolean) {
|
||||
applySelectableState(selectable)
|
||||
}
|
||||
|
||||
fun setContextMenuItems(
|
||||
items: List<String>,
|
||||
onPress: (itemText: String, selectedText: String, selectionStart: Int, selectionEnd: Int) -> Unit,
|
||||
) {
|
||||
contextMenuItemTexts = items
|
||||
onContextMenuItemPress = onPress
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (checkboxTouchHelper.onTouchEvent(event)) {
|
||||
if (event.action == MotionEvent.ACTION_DOWN) {
|
||||
cancelJSTouchForCheckboxTap(event)
|
||||
}
|
||||
return true
|
||||
}
|
||||
val result = super.onTouchEvent(event)
|
||||
when (event.action) {
|
||||
MotionEvent.ACTION_DOWN -> cancelJSTouchForLinkTap(event)
|
||||
else -> reallowParentInterceptIfLinkReleased()
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun setJustificationMode(needsJustify: Boolean) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
justificationMode =
|
||||
if (needsJustify) {
|
||||
Layout.JUSTIFICATION_MODE_INTER_WORD
|
||||
} else {
|
||||
Layout.JUSTIFICATION_MODE_NONE
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+404
@@ -0,0 +1,404 @@
|
||||
package com.swmansion.enriched.markdown
|
||||
|
||||
import android.content.Context
|
||||
import com.facebook.react.bridge.ReadableArray
|
||||
import com.facebook.react.bridge.ReadableMap
|
||||
import com.facebook.react.module.annotations.ReactModule
|
||||
import com.facebook.react.uimanager.ReactStylesDiffMap
|
||||
import com.facebook.react.uimanager.SimpleViewManager
|
||||
import com.facebook.react.uimanager.StateWrapper
|
||||
import com.facebook.react.uimanager.ThemedReactContext
|
||||
import com.facebook.react.uimanager.ViewManagerDelegate
|
||||
import com.facebook.react.uimanager.annotations.ReactProp
|
||||
import com.facebook.react.viewmanagers.EnrichedMarkdownManagerDelegate
|
||||
import com.facebook.react.viewmanagers.EnrichedMarkdownManagerInterface
|
||||
import com.facebook.yoga.YogaMeasureMode
|
||||
import com.swmansion.enriched.markdown.spoiler.SpoilerOverlay
|
||||
import com.swmansion.enriched.markdown.utils.common.CodeBlockStreamingMode
|
||||
import com.swmansion.enriched.markdown.utils.common.TableStreamingMode
|
||||
import com.swmansion.enriched.markdown.utils.common.applyReactBorderProps
|
||||
import com.swmansion.enriched.markdown.utils.common.emitCodeBlockPress
|
||||
import com.swmansion.enriched.markdown.utils.common.emitContextMenuItemPress
|
||||
import com.swmansion.enriched.markdown.utils.common.emitCopyPress
|
||||
import com.swmansion.enriched.markdown.utils.common.emitLatexError
|
||||
import com.swmansion.enriched.markdown.utils.common.emitLinkLongPress
|
||||
import com.swmansion.enriched.markdown.utils.common.emitLinkPress
|
||||
import com.swmansion.enriched.markdown.utils.common.emitTaskListItemPress
|
||||
import com.swmansion.enriched.markdown.utils.common.markdownEventTypeConstants
|
||||
import com.swmansion.enriched.markdown.utils.common.parseAccessibilityLabels
|
||||
import com.swmansion.enriched.markdown.utils.common.parseContextMenuItems
|
||||
import com.swmansion.enriched.markdown.utils.common.parseImageRequestHeaders
|
||||
import com.swmansion.enriched.markdown.utils.common.parseLinkPillContent
|
||||
import com.swmansion.enriched.markdown.utils.common.parseLinkRecognition
|
||||
import com.swmansion.enriched.markdown.utils.common.parseMd4cFlags
|
||||
import com.swmansion.enriched.markdown.utils.common.parseSelectionMenuConfig
|
||||
import com.swmansion.enriched.markdown.utils.text.interaction.TaskListToggleUtils
|
||||
|
||||
@ReactModule(name = EnrichedMarkdownManager.NAME)
|
||||
class EnrichedMarkdownManager :
|
||||
SimpleViewManager<EnrichedMarkdown>(),
|
||||
EnrichedMarkdownManagerInterface<EnrichedMarkdown> {
|
||||
private val mDelegate: ViewManagerDelegate<EnrichedMarkdown> = EnrichedMarkdownManagerDelegate(this)
|
||||
|
||||
override fun getDelegate(): ViewManagerDelegate<EnrichedMarkdown>? = mDelegate
|
||||
|
||||
override fun getName(): String = NAME
|
||||
|
||||
override fun createViewInstance(reactContext: ThemedReactContext): EnrichedMarkdown {
|
||||
val view = EnrichedMarkdown(reactContext)
|
||||
view.onContextMenuItemPressCallback = { itemText, selectedText, selectionStart, selectionEnd ->
|
||||
emitContextMenuItemPress(view, itemText, selectedText, selectionStart, selectionEnd)
|
||||
}
|
||||
|
||||
view.setOnLinkPressCallback { url, sourceType ->
|
||||
emitLinkPress(view, url, sourceType)
|
||||
}
|
||||
|
||||
view.setOnLinkLongPressCallback { url ->
|
||||
emitLinkLongPress(view, url)
|
||||
}
|
||||
|
||||
view.setOnTaskListItemPressCallback { taskIndex, checked, itemText ->
|
||||
val newChecked = !checked
|
||||
val updatedMarkdown = TaskListToggleUtils.toggleAtIndex(view.currentMarkdown, taskIndex, newChecked)
|
||||
view.setMarkdownContent(updatedMarkdown)
|
||||
view.commitProps()
|
||||
emitTaskListItemPress(view, taskIndex, newChecked, itemText)
|
||||
}
|
||||
|
||||
view.setOnCopyPressCallback { code, language ->
|
||||
emitCopyPress(view, code, language)
|
||||
}
|
||||
|
||||
view.setOnLatexErrorCallback { source, message, displayMode ->
|
||||
emitLatexError(view, source, message, displayMode)
|
||||
}
|
||||
|
||||
view.setOnCodeBlockPressCallback { code, language ->
|
||||
emitCodeBlockPress(view, code, language)
|
||||
}
|
||||
|
||||
return view
|
||||
}
|
||||
|
||||
override fun onAfterUpdateTransaction(view: EnrichedMarkdown) {
|
||||
super.onAfterUpdateTransaction(view)
|
||||
view.commitProps()
|
||||
}
|
||||
|
||||
// Replay containerStyle border props the delegate drops (see applyReactBorderProps).
|
||||
override fun updateProperties(
|
||||
view: EnrichedMarkdown,
|
||||
props: ReactStylesDiffMap,
|
||||
) {
|
||||
super.updateProperties(view, props)
|
||||
applyReactBorderProps(view, props)
|
||||
}
|
||||
|
||||
override fun updateState(
|
||||
view: EnrichedMarkdown,
|
||||
props: ReactStylesDiffMap?,
|
||||
stateWrapper: StateWrapper?,
|
||||
): Any? {
|
||||
view.stateWrapper = stateWrapper
|
||||
return super.updateState(view, props, stateWrapper)
|
||||
}
|
||||
|
||||
override fun onDropViewInstance(view: EnrichedMarkdown) {
|
||||
super.onDropViewInstance(view)
|
||||
view.cleanup()
|
||||
MeasurementStore.release(view.id)
|
||||
MeasurementStore.clearStreamingTableMode(view.id)
|
||||
MeasurementStore.clearStreamingCodeBlockMode(view.id)
|
||||
MeasurementStore.clearBreakStrategy(view.id)
|
||||
MeasurementStore.clearFontScalingSettings(view.id)
|
||||
}
|
||||
|
||||
override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> = markdownEventTypeConstants()
|
||||
|
||||
@ReactProp(name = "markdown")
|
||||
override fun setMarkdown(
|
||||
view: EnrichedMarkdown?,
|
||||
markdown: String?,
|
||||
) {
|
||||
view?.setMarkdownContent(markdown ?: "")
|
||||
}
|
||||
|
||||
@ReactProp(name = "markdownStyle")
|
||||
override fun setMarkdownStyle(
|
||||
view: EnrichedMarkdown?,
|
||||
style: ReadableMap?,
|
||||
) {
|
||||
view?.setMarkdownStyle(style)
|
||||
}
|
||||
|
||||
@ReactProp(name = "selectable", defaultBoolean = true)
|
||||
override fun setSelectable(
|
||||
view: EnrichedMarkdown?,
|
||||
selectable: Boolean,
|
||||
) {
|
||||
view?.setIsSelectable(selectable)
|
||||
}
|
||||
|
||||
override fun setSelectionColor(
|
||||
view: EnrichedMarkdown?,
|
||||
value: Int?,
|
||||
) {
|
||||
view?.setSelectionColor(value)
|
||||
}
|
||||
|
||||
override fun setSelectionHandleColor(
|
||||
view: EnrichedMarkdown?,
|
||||
value: Int?,
|
||||
) {
|
||||
view?.setSelectionHandleColor(value)
|
||||
}
|
||||
|
||||
@ReactProp(name = "linkRecognition")
|
||||
override fun setLinkRecognition(
|
||||
view: EnrichedMarkdown?,
|
||||
value: ReadableMap?,
|
||||
) {
|
||||
val recognition = parseLinkRecognition(value)
|
||||
view?.setLinkRegex(recognition.text)
|
||||
view?.setInlineCodeLinkRegex(recognition.inlineCode)
|
||||
}
|
||||
|
||||
@ReactProp(name = "md4cFlags")
|
||||
override fun setMd4cFlags(
|
||||
view: EnrichedMarkdown?,
|
||||
flags: ReadableMap?,
|
||||
) {
|
||||
view?.setMd4cFlags(parseMd4cFlags(flags))
|
||||
}
|
||||
|
||||
@ReactProp(name = "isGFM", defaultBoolean = true)
|
||||
override fun setIsGFM(
|
||||
view: EnrichedMarkdown?,
|
||||
isGFM: Boolean,
|
||||
) {
|
||||
view?.setIsGFM(isGFM)
|
||||
}
|
||||
|
||||
@ReactProp(name = "allowFontScaling", defaultBoolean = true)
|
||||
override fun setAllowFontScaling(
|
||||
view: EnrichedMarkdown?,
|
||||
allowFontScaling: Boolean,
|
||||
) {
|
||||
view?.setAllowFontScaling(allowFontScaling)
|
||||
}
|
||||
|
||||
@ReactProp(name = "maxFontSizeMultiplier", defaultFloat = 0f)
|
||||
override fun setMaxFontSizeMultiplier(
|
||||
view: EnrichedMarkdown?,
|
||||
maxFontSizeMultiplier: Float,
|
||||
) {
|
||||
view?.setMaxFontSizeMultiplier(maxFontSizeMultiplier)
|
||||
}
|
||||
|
||||
@ReactProp(name = "allowTrailingMargin", defaultBoolean = false)
|
||||
override fun setAllowTrailingMargin(
|
||||
view: EnrichedMarkdown?,
|
||||
allowTrailingMargin: Boolean,
|
||||
) {
|
||||
view?.setAllowTrailingMargin(allowTrailingMargin)
|
||||
}
|
||||
|
||||
@ReactProp(name = "enableLinkPreview", defaultBoolean = true)
|
||||
override fun setEnableLinkPreview(
|
||||
view: EnrichedMarkdown?,
|
||||
enableLinkPreview: Boolean,
|
||||
) {
|
||||
// No-op on Android — only used on iOS
|
||||
}
|
||||
|
||||
@ReactProp(name = "enableTaskListItemToggle", defaultBoolean = true)
|
||||
override fun setEnableTaskListItemToggle(
|
||||
view: EnrichedMarkdown?,
|
||||
enableTaskListItemToggle: Boolean,
|
||||
) {
|
||||
view?.enableTaskListItemToggle = enableTaskListItemToggle
|
||||
}
|
||||
|
||||
@ReactProp(name = "enableImagePress", defaultBoolean = false)
|
||||
override fun setEnableImagePress(
|
||||
view: EnrichedMarkdown?,
|
||||
enableImagePress: Boolean,
|
||||
) {
|
||||
view?.setEnableImagePress(enableImagePress)
|
||||
}
|
||||
|
||||
@ReactProp(name = "enableBlockContextMenu", defaultBoolean = true)
|
||||
override fun setEnableBlockContextMenu(
|
||||
view: EnrichedMarkdown?,
|
||||
enableBlockContextMenu: Boolean,
|
||||
) {
|
||||
view?.enableBlockContextMenu = enableBlockContextMenu
|
||||
}
|
||||
|
||||
@ReactProp(name = "enableCodeBlockPress", defaultBoolean = false)
|
||||
override fun setEnableCodeBlockPress(
|
||||
view: EnrichedMarkdown?,
|
||||
enableCodeBlockPress: Boolean,
|
||||
) {
|
||||
view?.enableCodeBlockPress = enableCodeBlockPress
|
||||
}
|
||||
|
||||
@ReactProp(name = "lineBreakStrategyIOS")
|
||||
override fun setLineBreakStrategyIOS(
|
||||
view: EnrichedMarkdown?,
|
||||
strategy: String?,
|
||||
) {
|
||||
// No-op on Android — only used on iOS
|
||||
}
|
||||
|
||||
@ReactProp(name = "writingDirection")
|
||||
override fun setWritingDirection(
|
||||
view: EnrichedMarkdown?,
|
||||
value: String?,
|
||||
) {
|
||||
// No-op on Android — first-strong per-paragraph resolution is the platform default
|
||||
}
|
||||
|
||||
@ReactProp(name = "streamingAnimation", defaultBoolean = false)
|
||||
override fun setStreamingAnimation(
|
||||
view: EnrichedMarkdown?,
|
||||
streamingAnimation: Boolean,
|
||||
) {
|
||||
view?.streamingAnimation = streamingAnimation
|
||||
}
|
||||
|
||||
@ReactProp(name = "streamingConfig")
|
||||
override fun setStreamingConfig(
|
||||
view: EnrichedMarkdown?,
|
||||
config: ReadableMap?,
|
||||
) {
|
||||
if (view == null) return
|
||||
val tableMode =
|
||||
when (config?.getString("tableMode")) {
|
||||
"hidden" -> TableStreamingMode.HIDDEN
|
||||
else -> TableStreamingMode.PROGRESSIVE
|
||||
}
|
||||
view.tableStreamingMode = tableMode
|
||||
view.codeBlockStreamingMode =
|
||||
when (config?.getString("codeBlockMode")) {
|
||||
"hidden" -> CodeBlockStreamingMode.HIDDEN
|
||||
else -> CodeBlockStreamingMode.PROGRESSIVE
|
||||
}
|
||||
}
|
||||
|
||||
@ReactProp(name = "spoilerOverlay")
|
||||
override fun setSpoilerOverlay(
|
||||
view: EnrichedMarkdown?,
|
||||
mode: String?,
|
||||
) {
|
||||
view?.spoilerOverlay = SpoilerOverlay.fromString(mode)
|
||||
}
|
||||
|
||||
@ReactProp(name = "textBreakStrategy")
|
||||
override fun setTextBreakStrategy(
|
||||
view: EnrichedMarkdown?,
|
||||
strategy: String?,
|
||||
) {
|
||||
view?.setTextBreakStrategy(strategy ?: "highQuality")
|
||||
}
|
||||
|
||||
@ReactProp(name = "numberOfLines", defaultInt = 0)
|
||||
override fun setNumberOfLines(
|
||||
view: EnrichedMarkdown?,
|
||||
value: Int,
|
||||
) {
|
||||
// No-op for GFM — block segments cannot honor a document-wide line cap. See the GFM tracking issue.
|
||||
}
|
||||
|
||||
@ReactProp(name = "ellipsizeMode")
|
||||
override fun setEllipsizeMode(
|
||||
view: EnrichedMarkdown?,
|
||||
value: String?,
|
||||
) {
|
||||
// No-op for GFM — see setNumberOfLines.
|
||||
}
|
||||
|
||||
@ReactProp(name = "linkContextMenuItems")
|
||||
override fun setLinkContextMenuItems(
|
||||
view: EnrichedMarkdown?,
|
||||
value: ReadableArray?,
|
||||
) {
|
||||
// Link menus are iOS-only for now; onLinkLongPress is the Android hook.
|
||||
}
|
||||
|
||||
@ReactProp(name = "contextMenuItems")
|
||||
override fun setContextMenuItems(
|
||||
view: EnrichedMarkdown?,
|
||||
value: ReadableArray?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.setContextMenuItems(parseContextMenuItems(value))
|
||||
}
|
||||
|
||||
@ReactProp(name = "imageRequestHeaders")
|
||||
override fun setImageRequestHeaders(
|
||||
view: EnrichedMarkdown?,
|
||||
value: ReadableArray?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.setImageRequestHeaders(parseImageRequestHeaders(value))
|
||||
}
|
||||
|
||||
@ReactProp(name = "linkPillContent")
|
||||
override fun setLinkPillContent(
|
||||
view: EnrichedMarkdown?,
|
||||
value: ReadableArray?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.setLinkPillContent(parseLinkPillContent(value))
|
||||
}
|
||||
|
||||
@ReactProp(name = "selectionMenuConfig")
|
||||
override fun setSelectionMenuConfig(
|
||||
view: EnrichedMarkdown?,
|
||||
value: ReadableMap?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.setSelectionMenuConfig(parseSelectionMenuConfig(value))
|
||||
}
|
||||
|
||||
@ReactProp(name = "accessibilityLabels")
|
||||
override fun setAccessibilityLabels(
|
||||
view: EnrichedMarkdown?,
|
||||
value: ReadableMap?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.setAccessibilityLabels(parseAccessibilityLabels(value))
|
||||
}
|
||||
|
||||
override fun setPadding(
|
||||
view: EnrichedMarkdown,
|
||||
left: Int,
|
||||
top: Int,
|
||||
right: Int,
|
||||
bottom: Int,
|
||||
) {
|
||||
super.setPadding(view, left, top, right, bottom)
|
||||
view.setPadding(left, top, right, bottom)
|
||||
}
|
||||
|
||||
override fun measure(
|
||||
context: Context,
|
||||
localData: ReadableMap?,
|
||||
props: ReadableMap?,
|
||||
state: ReadableMap?,
|
||||
width: Float,
|
||||
widthMode: YogaMeasureMode?,
|
||||
height: Float,
|
||||
heightMode: YogaMeasureMode?,
|
||||
attachmentsPositions: FloatArray?,
|
||||
): Long {
|
||||
val id = localData?.getInt("viewTag")
|
||||
return MeasurementStore.getMeasureById(context, id, width, widthMode, height, heightMode, props, splitTableSegments = true)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val NAME = "EnrichedMarkdown"
|
||||
}
|
||||
}
|
||||
+633
@@ -0,0 +1,633 @@
|
||||
package com.swmansion.enriched.markdown
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Canvas
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.text.Layout
|
||||
import android.util.AttributeSet
|
||||
import android.util.Log
|
||||
import android.util.TypedValue
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.View.MeasureSpec
|
||||
import com.facebook.react.bridge.ReadableMap
|
||||
import com.facebook.react.uimanager.BackgroundStyleApplicator
|
||||
import com.facebook.react.uimanager.PixelUtil
|
||||
import com.facebook.react.uimanager.StateWrapper
|
||||
import com.facebook.react.uimanager.style.LogicalEdge
|
||||
import com.swmansion.enriched.markdown.accessibility.AccessibilityLabels
|
||||
import com.swmansion.enriched.markdown.accessibility.AccessibleMarkdownTextView
|
||||
import com.swmansion.enriched.markdown.math.LatexErrorReporter
|
||||
import com.swmansion.enriched.markdown.parser.Md4cFlags
|
||||
import com.swmansion.enriched.markdown.parser.Parser
|
||||
import com.swmansion.enriched.markdown.renderer.Renderer
|
||||
import com.swmansion.enriched.markdown.spoiler.SpoilerCapable
|
||||
import com.swmansion.enriched.markdown.spoiler.SpoilerOverlay
|
||||
import com.swmansion.enriched.markdown.spoiler.SpoilerOverlayDrawer
|
||||
import com.swmansion.enriched.markdown.styles.LinkPillContent
|
||||
import com.swmansion.enriched.markdown.styles.StyleConfig
|
||||
import com.swmansion.enriched.markdown.utils.common.BreakStrategyUtils
|
||||
import com.swmansion.enriched.markdown.utils.common.EllipsizeUtils
|
||||
import com.swmansion.enriched.markdown.utils.common.LinkRegexConfig
|
||||
import com.swmansion.enriched.markdown.utils.common.emitCodeBlockPress
|
||||
import com.swmansion.enriched.markdown.utils.text.TailFadeInAnimator
|
||||
import com.swmansion.enriched.markdown.utils.text.interaction.CheckboxTouchHelper
|
||||
import com.swmansion.enriched.markdown.utils.text.view.CodeBlockPressHost
|
||||
import com.swmansion.enriched.markdown.utils.text.view.ImagePressHost
|
||||
import com.swmansion.enriched.markdown.utils.text.view.LinkLongPressMovementMethod
|
||||
import com.swmansion.enriched.markdown.utils.text.view.SelectionMenuConfig
|
||||
import com.swmansion.enriched.markdown.utils.text.view.applySelectableState
|
||||
import com.swmansion.enriched.markdown.utils.text.view.applySelectionColors
|
||||
import com.swmansion.enriched.markdown.utils.text.view.cancelJSTouchForCheckboxTap
|
||||
import com.swmansion.enriched.markdown.utils.text.view.cancelJSTouchForLinkTap
|
||||
import com.swmansion.enriched.markdown.utils.text.view.createSelectionActionModeCallback
|
||||
import com.swmansion.enriched.markdown.utils.text.view.emitImagePressEvent
|
||||
import com.swmansion.enriched.markdown.utils.text.view.emitLinkLongPressEvent
|
||||
import com.swmansion.enriched.markdown.utils.text.view.emitLinkPressEvent
|
||||
import com.swmansion.enriched.markdown.utils.text.view.reallowParentInterceptIfLinkReleased
|
||||
import com.swmansion.enriched.markdown.utils.text.view.setupAsMarkdownTextView
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* EnrichedMarkdownText that handles Markdown parsing and rendering on a background thread.
|
||||
* View starts invisible and becomes visible after render completes to avoid layout shift.
|
||||
*/
|
||||
class EnrichedMarkdownText
|
||||
@JvmOverloads
|
||||
constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
defStyleAttr: Int = 0,
|
||||
) : AccessibleMarkdownTextView(context, attrs, defStyleAttr),
|
||||
SpoilerCapable,
|
||||
ImagePressHost,
|
||||
CodeBlockPressHost {
|
||||
private val parser = Parser.shared
|
||||
private val renderer = Renderer()
|
||||
private var onLinkPressCallback: ((String, String) -> Unit)? = null
|
||||
private var onLinkLongPressCallback: ((String) -> Unit)? = null
|
||||
private var onLatexErrorCallback: LatexErrorReporter? = null
|
||||
|
||||
private val reportedLatexErrors = HashSet<String>()
|
||||
|
||||
private val latexErrorReporter =
|
||||
LatexErrorReporter { source, message, displayMode ->
|
||||
val key = (if (displayMode) "B " else "I ") + source
|
||||
if (reportedLatexErrors.add(key)) {
|
||||
onLatexErrorCallback?.report(source, message, displayMode)
|
||||
}
|
||||
}
|
||||
private val checkboxTouchHelper = CheckboxTouchHelper(this)
|
||||
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
private var currentRenderId = 0L
|
||||
|
||||
val layoutManager = EnrichedMarkdownTextLayoutManager(this)
|
||||
|
||||
// used to force a Yoga re-measure when a block image resolves its box height
|
||||
var stateWrapper: StateWrapper? = null
|
||||
|
||||
private var contextMenuItemTexts: List<String> = emptyList()
|
||||
var onContextMenuItemPressCallback: ((itemText: String, selectedText: String, selectionStart: Int, selectionEnd: Int) -> Unit)? = null
|
||||
|
||||
var markdownStyle: StyleConfig? = null
|
||||
private set
|
||||
|
||||
var currentMarkdown: String = ""
|
||||
private set
|
||||
|
||||
var md4cFlags: Md4cFlags = Md4cFlags.DEFAULT
|
||||
private set
|
||||
private var linkRegex: LinkRegexConfig? = null
|
||||
private var inlineCodeLinkRegex: LinkRegexConfig? = null
|
||||
private var isGFM: Boolean = false
|
||||
|
||||
private var lastKnownFontScale: Float = context.resources.configuration.fontScale
|
||||
private var markdownStyleMap: ReadableMap? = null
|
||||
|
||||
private var allowFontScaling: Boolean = true
|
||||
private var maxFontSizeMultiplier: Float = 0f
|
||||
private var allowTrailingMargin: Boolean = false
|
||||
private var imageRequestHeaders: Map<String, String> = emptyMap()
|
||||
private var linkPillContent: Map<String, LinkPillContent> = emptyMap()
|
||||
|
||||
private var streamingAnimation: Boolean = false
|
||||
private var previousTextLength: Int = 0
|
||||
private var fadeAnimator: TailFadeInAnimator? = null
|
||||
override var spoilerOverlayDrawer: SpoilerOverlayDrawer? = null
|
||||
private set
|
||||
var spoilerOverlay: SpoilerOverlay = SpoilerOverlay.PARTICLES
|
||||
|
||||
private var pendingStyledText: CharSequence? = null
|
||||
|
||||
private var mdNumberOfLines: Int = 0
|
||||
private var mdEllipsizeMode: String = EllipsizeUtils.DEFAULT_MODE
|
||||
private var mdSelectable: Boolean = true
|
||||
|
||||
private var selectionColor: Int? = null
|
||||
private var selectionHandleColor: Int? = null
|
||||
private var selectionMenuConfig = SelectionMenuConfig()
|
||||
private var baseHorizontalPaddingLeft = 0
|
||||
private var baseHorizontalPaddingRight = 0
|
||||
private var applyingContentBoxInset = false
|
||||
|
||||
init {
|
||||
setupAsMarkdownTextView()
|
||||
customSelectionActionModeCallback =
|
||||
createSelectionActionModeCallback(
|
||||
this,
|
||||
getCustomItemTexts = { contextMenuItemTexts },
|
||||
getSelectionMenuConfig = { selectionMenuConfig },
|
||||
onCustomItemPress = { itemText, selectedText, start, end ->
|
||||
onContextMenuItemPressCallback?.invoke(itemText, selectedText, start, end)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fun setMarkdownContent(markdown: String) {
|
||||
if (currentMarkdown == markdown) return
|
||||
currentMarkdown = markdown
|
||||
scheduleRender()
|
||||
}
|
||||
|
||||
fun setMarkdownStyle(style: ReadableMap?) {
|
||||
markdownStyleMap = style
|
||||
// Register font scaling settings when style is set (view should have ID by now)
|
||||
updateMeasurementStoreFontScaling()
|
||||
val newStyle = style?.let { StyleConfig(it, context, allowFontScaling, maxFontSizeMultiplier) }
|
||||
newStyle?.imageRequestHeaders = imageRequestHeaders
|
||||
newStyle?.linkPillContent = linkPillContent
|
||||
if (markdownStyle == newStyle) return
|
||||
markdownStyle = newStyle
|
||||
updateJustificationMode(newStyle)
|
||||
scheduleRender()
|
||||
}
|
||||
|
||||
fun setImageRequestHeaders(headers: Map<String, String>) {
|
||||
if (imageRequestHeaders == headers) return
|
||||
imageRequestHeaders = headers
|
||||
markdownStyle?.imageRequestHeaders = headers
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
fun setLinkPillContent(content: Map<String, LinkPillContent>) {
|
||||
if (linkPillContent == content) return
|
||||
linkPillContent = content
|
||||
markdownStyle?.linkPillContent = content
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
|
||||
if (!allowFontScaling) {
|
||||
return
|
||||
}
|
||||
|
||||
val newFontScale = newConfig.fontScale
|
||||
if (newFontScale != lastKnownFontScale) {
|
||||
lastKnownFontScale = newFontScale
|
||||
recreateStyleConfig()
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
fun setLinkRegex(config: LinkRegexConfig?) {
|
||||
if (linkRegex == config) return
|
||||
linkRegex = config
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
fun setInlineCodeLinkRegex(config: LinkRegexConfig?) {
|
||||
if (inlineCodeLinkRegex == config) return
|
||||
inlineCodeLinkRegex = config
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
fun setMd4cFlags(flags: Md4cFlags) {
|
||||
if (md4cFlags == flags) return
|
||||
md4cFlags = flags
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
fun setIsGFM(value: Boolean) {
|
||||
if (isGFM == value) return
|
||||
isGFM = value
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
fun setAllowFontScaling(allow: Boolean) {
|
||||
if (allowFontScaling == allow) return
|
||||
allowFontScaling = allow
|
||||
updateMeasurementStoreFontScaling()
|
||||
recreateStyleConfig()
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
fun setMaxFontSizeMultiplier(multiplier: Float) {
|
||||
if (maxFontSizeMultiplier == multiplier) return
|
||||
maxFontSizeMultiplier = multiplier
|
||||
updateMeasurementStoreFontScaling()
|
||||
recreateStyleConfig()
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
fun setAllowTrailingMargin(allow: Boolean) {
|
||||
if (allowTrailingMargin == allow) return
|
||||
allowTrailingMargin = allow
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
fun setStreamingAnimation(enabled: Boolean) {
|
||||
if (streamingAnimation == enabled) return
|
||||
streamingAnimation = enabled
|
||||
if (enabled) {
|
||||
previousTextLength = text?.length ?: 0
|
||||
} else {
|
||||
fadeAnimator?.cancelAll()
|
||||
fadeAnimator = null
|
||||
previousTextLength = 0
|
||||
}
|
||||
}
|
||||
|
||||
fun commitProps() {
|
||||
updateMeasurementStoreFontScaling()
|
||||
}
|
||||
|
||||
private fun updateMeasurementStoreFontScaling() {
|
||||
MeasurementStore.updateFontScalingSettings(id, allowFontScaling, maxFontSizeMultiplier)
|
||||
}
|
||||
|
||||
private fun scheduleRenderIfNeeded() {
|
||||
if (currentMarkdown.isNotEmpty()) {
|
||||
scheduleRender()
|
||||
}
|
||||
}
|
||||
|
||||
private fun recreateStyleConfig() {
|
||||
markdownStyleMap?.let { styleMap ->
|
||||
markdownStyle =
|
||||
StyleConfig(styleMap, context, allowFontScaling, maxFontSizeMultiplier).also {
|
||||
it.imageRequestHeaders = imageRequestHeaders
|
||||
it.linkPillContent = linkPillContent
|
||||
}
|
||||
updateJustificationMode(markdownStyle)
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateJustificationMode(style: StyleConfig?) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
justificationMode =
|
||||
if (style?.needsJustify == true) {
|
||||
Layout.JUSTIFICATION_MODE_INTER_WORD
|
||||
} else {
|
||||
Layout.JUSTIFICATION_MODE_NONE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun scheduleRender() {
|
||||
val style = markdownStyle ?: return
|
||||
val markdown = currentMarkdown
|
||||
if (markdown.isEmpty()) return
|
||||
|
||||
val textLinkRegex = linkRegex
|
||||
val codeLinkRegex = inlineCodeLinkRegex
|
||||
val renderId = ++currentRenderId
|
||||
|
||||
executor.execute {
|
||||
try {
|
||||
val ast =
|
||||
parser.parseMarkdown(markdown, md4cFlags, isGFM, textLinkRegex, codeLinkRegex) ?: run {
|
||||
mainHandler.post { if (renderId == currentRenderId && isAttachedToWindow) text = "" }
|
||||
return@execute
|
||||
}
|
||||
|
||||
renderer.configure(style, context, latexErrorReporter)
|
||||
val styledText = renderer.renderDocument(ast, onLinkPressCallback, onLinkLongPressCallback)
|
||||
|
||||
mainHandler.post {
|
||||
if (renderId == currentRenderId) {
|
||||
if (isAttachedToWindow) {
|
||||
applyRenderedText(styledText)
|
||||
} else {
|
||||
pendingStyledText = styledText
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Render failed: ${e.message}", e)
|
||||
mainHandler.post { if (renderId == currentRenderId && isAttachedToWindow) text = "" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyRenderedText(styledText: CharSequence) {
|
||||
val tailStart = previousTextLength
|
||||
|
||||
markdownStyle?.paragraphStyle?.fontSize?.let {
|
||||
setTextSize(TypedValue.COMPLEX_UNIT_PX, it)
|
||||
}
|
||||
|
||||
text = styledText
|
||||
|
||||
applyInteractivity()
|
||||
|
||||
renderer.getCollectedImageSpans().forEach { span ->
|
||||
span.registerTextView(this)
|
||||
}
|
||||
|
||||
spoilerOverlayDrawer = SpoilerOverlayDrawer.setupIfNeeded(this, styledText, spoilerOverlayDrawer, spoilerOverlay)
|
||||
|
||||
layoutManager.invalidateLayout()
|
||||
accessibilityHelper.invalidateAccessibilityItems()
|
||||
|
||||
if (streamingAnimation) {
|
||||
if (fadeAnimator == null) {
|
||||
fadeAnimator = TailFadeInAnimator(this)
|
||||
}
|
||||
fadeAnimator?.animate(tailStart, styledText.length)
|
||||
previousTextLength = styledText.length
|
||||
}
|
||||
|
||||
applySelectionColors(selectionColor, selectionHandleColor)
|
||||
}
|
||||
|
||||
// Trailing bottom margin included in the shadow-node measurement — must be
|
||||
// mirrored when re-storing the measurement from the display text.
|
||||
fun trailingMarginBottomPx(): Float = if (allowTrailingMargin) renderer.getLastElementMarginBottom() else 0f
|
||||
|
||||
fun setContextMenuItems(items: List<String>) {
|
||||
contextMenuItemTexts = items
|
||||
}
|
||||
|
||||
fun setSelectionMenuConfig(config: SelectionMenuConfig) {
|
||||
if (selectionMenuConfig == config) return
|
||||
selectionMenuConfig = config
|
||||
}
|
||||
|
||||
fun setAccessibilityLabels(labels: AccessibilityLabels) {
|
||||
accessibilityHelper.labels = labels
|
||||
}
|
||||
|
||||
fun setIsSelectable(selectable: Boolean) {
|
||||
mdSelectable = selectable
|
||||
applyInteractivity()
|
||||
}
|
||||
|
||||
fun setSelectionColor(color: Int?) {
|
||||
if (selectionColor == color) return
|
||||
selectionColor = color
|
||||
applySelectionColors(selectionColor, selectionHandleColor)
|
||||
}
|
||||
|
||||
fun setSelectionHandleColor(color: Int?) {
|
||||
if (selectionHandleColor == color) return
|
||||
selectionHandleColor = color
|
||||
applySelectionColors(selectionColor, selectionHandleColor)
|
||||
}
|
||||
|
||||
fun setTextBreakStrategy(strategy: String) {
|
||||
MeasurementStore.updateBreakStrategy(id, strategy)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
breakStrategy = BreakStrategyUtils.resolveBreakStrategy(strategy)
|
||||
}
|
||||
MeasurementStore.invalidate(id)
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
fun setMarkdownNumberOfLines(value: Int) {
|
||||
val normalized = value.coerceAtLeast(0)
|
||||
if (mdNumberOfLines == normalized) return
|
||||
mdNumberOfLines = normalized
|
||||
MeasurementStore.updateNumberOfLines(id, normalized)
|
||||
applyLineLimitToView()
|
||||
MeasurementStore.invalidate(id)
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
fun setMarkdownEllipsizeMode(value: String) {
|
||||
if (mdEllipsizeMode == value) return
|
||||
mdEllipsizeMode = value
|
||||
MeasurementStore.updateEllipsizeMode(id, value)
|
||||
applyLineLimitToView()
|
||||
MeasurementStore.invalidate(id)
|
||||
scheduleRenderIfNeeded()
|
||||
}
|
||||
|
||||
// Mirrors RN's ReactTextView.updateView: only ellipsize when a line limit is
|
||||
// set; unlimited restores the default unbounded, non-ellipsized state.
|
||||
private fun applyLineLimitToView() {
|
||||
if (mdNumberOfLines > 0) {
|
||||
maxLines = mdNumberOfLines
|
||||
ellipsize = EllipsizeUtils.resolveTruncateAt(mdEllipsizeMode)
|
||||
} else {
|
||||
maxLines = Integer.MAX_VALUE
|
||||
ellipsize = null
|
||||
}
|
||||
applyInteractivity()
|
||||
}
|
||||
|
||||
// The numberOfLines ellipsis and text selection / link taps are mutually
|
||||
// exclusive on Android and cannot be reconciled. Both setTextIsSelectable(true)
|
||||
// and a non-null movementMethod force the display text to a Spannable, which
|
||||
// makes TextView pick DynamicLayout (TextView.useDynamicLayout). DynamicLayout
|
||||
// has no setMaxLines, so the clamp is never baked into the layout and no
|
||||
// ellipsis glyph is drawn (verified against AOSP TextView/DynamicLayout on
|
||||
// API 35/36). To keep the ellipsis, a clamped view must be non-selectable AND
|
||||
// drop its movement method; both are restored to the user's preference once
|
||||
// the clamp is removed.
|
||||
private fun applyInteractivity() {
|
||||
if (mdNumberOfLines > 0) {
|
||||
if (isTextSelectable) setTextIsSelectable(false)
|
||||
movementMethod = null
|
||||
} else {
|
||||
applySelectableState(mdSelectable)
|
||||
if (movementMethod !is LinkLongPressMovementMethod) {
|
||||
movementMethod = LinkLongPressMovementMethod.createInstance()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun emitOnLinkPress(url: String, sourceType: String) {
|
||||
emitLinkPressEvent(url, sourceType)
|
||||
}
|
||||
|
||||
fun emitOnLinkLongPress(url: String) {
|
||||
emitLinkLongPressEvent(url)
|
||||
}
|
||||
|
||||
override var imagePressEnabled: Boolean = false
|
||||
private set
|
||||
|
||||
override fun emitOnImagePress(
|
||||
url: String,
|
||||
altText: String,
|
||||
) {
|
||||
emitImagePressEvent(url, altText)
|
||||
}
|
||||
|
||||
fun setEnableImagePress(enabled: Boolean) {
|
||||
imagePressEnabled = enabled
|
||||
}
|
||||
|
||||
override var codeBlockPressEnabled: Boolean = false
|
||||
private set
|
||||
|
||||
override fun emitOnCodeBlockPress(
|
||||
code: String,
|
||||
language: String,
|
||||
) {
|
||||
emitCodeBlockPress(this, code, language)
|
||||
}
|
||||
|
||||
fun setEnableCodeBlockPress(enabled: Boolean) {
|
||||
codeBlockPressEnabled = enabled
|
||||
}
|
||||
|
||||
fun setOnLinkPressCallback(callback: (String, String) -> Unit) {
|
||||
onLinkPressCallback = callback
|
||||
}
|
||||
|
||||
fun setOnLinkLongPressCallback(callback: (String) -> Unit) {
|
||||
onLinkLongPressCallback = callback
|
||||
}
|
||||
|
||||
fun setOnLatexErrorCallback(callback: LatexErrorReporter) {
|
||||
onLatexErrorCallback = callback
|
||||
}
|
||||
|
||||
fun setOnTaskListItemPressCallback(callback: ((taskIndex: Int, checked: Boolean, itemText: String) -> Unit)?) {
|
||||
checkboxTouchHelper.onCheckboxTap = callback
|
||||
}
|
||||
|
||||
fun setEnableTaskListItemToggle(enabled: Boolean) {
|
||||
checkboxTouchHelper.isEnabled = enabled
|
||||
}
|
||||
|
||||
fun cleanup() {
|
||||
currentRenderId++
|
||||
executor.shutdownNow()
|
||||
mainHandler.removeCallbacksAndMessages(null)
|
||||
pendingStyledText = null
|
||||
fadeAnimator?.cancelAll()
|
||||
fadeAnimator = null
|
||||
}
|
||||
|
||||
override fun setPadding(
|
||||
left: Int,
|
||||
top: Int,
|
||||
right: Int,
|
||||
bottom: Int,
|
||||
) {
|
||||
if (!applyingContentBoxInset) {
|
||||
baseHorizontalPaddingLeft = left
|
||||
baseHorizontalPaddingRight = right
|
||||
}
|
||||
super.setPadding(left, top, right, bottom)
|
||||
}
|
||||
|
||||
override fun onMeasure(
|
||||
widthMeasureSpec: Int,
|
||||
heightMeasureSpec: Int,
|
||||
) {
|
||||
applyContentBoxInset(widthMeasureSpec)
|
||||
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fabric measures text at the content box (frame - padding - border) but the TextView's
|
||||
* padding carries no border, so it wraps ~1dp wider and reserves a phantom trailing line
|
||||
* under an unclamped box (#805). Fold the border into padding to match; restore the base
|
||||
* padding when the cache or an exact frame is missing so no stale inset lingers.
|
||||
*/
|
||||
private fun applyContentBoxInset(widthMeasureSpec: Int) {
|
||||
val contentBox =
|
||||
if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY) {
|
||||
MeasurementStore.contentBoxWidthPx(id)?.let { ceil(it).toInt() }?.takeIf { it > 0 }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val frame = MeasureSpec.getSize(widthMeasureSpec)
|
||||
if (contentBox == null || frame <= 0) {
|
||||
setHorizontalPadding(baseHorizontalPaddingLeft, baseHorizontalPaddingRight)
|
||||
return
|
||||
}
|
||||
|
||||
val totalInset = (frame - contentBox).coerceIn(0, frame)
|
||||
val left = (baseHorizontalPaddingLeft + resolvedBorderPx(leftEdge = true)).coerceIn(0, totalInset)
|
||||
val right = (totalInset - left).coerceAtLeast(0)
|
||||
setHorizontalPadding(left, right)
|
||||
}
|
||||
|
||||
// Physical border width (px); only the left/right split reads it, never the total inset.
|
||||
private fun resolvedBorderPx(leftEdge: Boolean): Int {
|
||||
val rtl = layoutDirection == View.LAYOUT_DIRECTION_RTL
|
||||
val physical = if (leftEdge) LogicalEdge.LEFT else LogicalEdge.RIGHT
|
||||
val logical = if (leftEdge != rtl) LogicalEdge.START else LogicalEdge.END
|
||||
val dp =
|
||||
BackgroundStyleApplicator.getBorderWidth(this, physical)
|
||||
?: BackgroundStyleApplicator.getBorderWidth(this, logical)
|
||||
?: BackgroundStyleApplicator.getBorderWidth(this, LogicalEdge.ALL)
|
||||
?: return 0
|
||||
return PixelUtil.toPixelFromDIP(dp).roundToInt().coerceAtLeast(0)
|
||||
}
|
||||
|
||||
private fun setHorizontalPadding(
|
||||
left: Int,
|
||||
right: Int,
|
||||
) {
|
||||
if (left == paddingLeft && right == paddingRight) return
|
||||
applyingContentBoxInset = true
|
||||
super.setPadding(left, paddingTop, right, paddingBottom)
|
||||
applyingContentBoxInset = false
|
||||
}
|
||||
|
||||
override fun onAttachedToWindow() {
|
||||
super.onAttachedToWindow()
|
||||
pendingStyledText?.let {
|
||||
pendingStyledText = null
|
||||
applyRenderedText(it)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
stopSpoilerAnimations()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
spoilerOverlayDrawer?.draw(canvas)
|
||||
}
|
||||
|
||||
private fun stopSpoilerAnimations() {
|
||||
spoilerOverlayDrawer?.stop()
|
||||
spoilerOverlayDrawer = null
|
||||
}
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
if (checkboxTouchHelper.onTouchEvent(event)) {
|
||||
if (event.action == MotionEvent.ACTION_DOWN) {
|
||||
cancelJSTouchForCheckboxTap(event)
|
||||
}
|
||||
return true
|
||||
}
|
||||
val result = super.onTouchEvent(event)
|
||||
when (event.action) {
|
||||
MotionEvent.ACTION_DOWN -> cancelJSTouchForLinkTap(event)
|
||||
else -> reallowParentInterceptIfLinkReleased()
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "EnrichedMarkdownMeasure"
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user