mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-23 00:35:28 +00:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5913fd2a2 | ||
|
|
43ec56d07f | ||
|
|
5251a74a6a | ||
|
|
a1ae05e56c | ||
|
|
eda906f6ee | ||
|
|
08ad7c7271 | ||
|
|
b2ecec8719 | ||
|
|
fa37fd20ca | ||
|
|
ff5a83bc5a | ||
|
|
9cb0625cf5 | ||
|
|
03adc4d4ba | ||
|
|
4b429c0030 | ||
|
|
20f217b8cb | ||
|
|
984e2ea5e7 | ||
|
|
133b078ac4 | ||
|
|
6ea095cb49 |
@@ -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/**"
|
||||
|
||||
@@ -278,8 +278,8 @@ jobs:
|
||||
|
||||
# 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. Scoped to the observer/watcher suites to
|
||||
# bound runtime.
|
||||
# otherwise has no server-test coverage. Keep this job scoped to regressions
|
||||
# reported on macOS.
|
||||
server-tests-macos:
|
||||
name: server-tests (macos-latest, file observation)
|
||||
needs: changes
|
||||
@@ -307,6 +307,12 @@ jobs:
|
||||
src/server/workspace-git-service.observation.integration.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
|
||||
|
||||
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
-1
@@ -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": {
|
||||
|
||||
+33
-31
@@ -2,75 +2,76 @@
|
||||
|
||||
## 0.17.1 - 2026-11-21
|
||||
|
||||
- **Use existing worktrees:** Start a workspace in a worktree you already have, or create one from a branch or pull request. Plugins can manage worktree creation, removal, and restoration. When you branch off a fork PR or MR, choose Run setup to approve workspace automation. ([#10190](https://github.com/getpaseo/paseo/pull/10190), [#10278](https://github.com/getpaseo/paseo/pull/10278))
|
||||
- **Update providers in Paseo:** See each provider's status, installed version, and available updates in the provider list. Open a provider's settings from Settings, setup, or the model picker to update supported CLIs and watch their output. ([#9568](https://github.com/getpaseo/paseo/pull/9568), [#9661](https://github.com/getpaseo/paseo/pull/9661))
|
||||
- **Provider quota forecasts:** Usage estimates when a quota will run out before reset based on your current pace, shown inline with the reset time. Healthy quota bars now show in green, and reset and exhaustion times include the weekday and calendar date when needed. ([#10289](https://github.com/getpaseo/paseo/pull/10289), [#10385](https://github.com/getpaseo/paseo/pull/10385), [#10397](https://github.com/getpaseo/paseo/pull/10397))
|
||||
- **Watch PRs and MRs:** Ask an agent to watch a GitHub, GitLab, Gitea, Forgejo, or Codeberg change request for updates to checks, reviews, or comments. Stop a watch from Background work. ([#10148](https://github.com/getpaseo/paseo/pull/10148), [#10279](https://github.com/getpaseo/paseo/pull/10279), [#10280](https://github.com/getpaseo/paseo/pull/10280))
|
||||
- **Antigravity approvals and history:** Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires [Antigravity CLI 1.5.0 or later](https://paseo.sh/docs/supported-providers/antigravity). ([#10193](https://github.com/getpaseo/paseo/pull/10193))
|
||||
- **Use existing worktrees:** Start a workspace in a worktree you already have, or create one from a branch or pull request. ([#10190](https://github.com/getpaseo/paseo/pull/10190))
|
||||
- **Update providers in Paseo:** See each provider's status and installed version, and update supported CLIs from the app. ([#9568](https://github.com/getpaseo/paseo/pull/9568), [#9661](https://github.com/getpaseo/paseo/pull/9661))
|
||||
- **Provider quota forecasts:** Usage shows when your current pace will use up a quota before it resets. ([#10289](https://github.com/getpaseo/paseo/pull/10289), [#10385](https://github.com/getpaseo/paseo/pull/10385))
|
||||
- **Watch PRs and MRs:** Ask an agent to watch a pull or merge request for new checks, reviews, and comments. ([#10148](https://github.com/getpaseo/paseo/pull/10148), [#10279](https://github.com/getpaseo/paseo/pull/10279), [#10280](https://github.com/getpaseo/paseo/pull/10280))
|
||||
- **Heartbeats in Background work:** See and stop an agent's heartbeats next to its background tasks. ([#10097](https://github.com/getpaseo/paseo/pull/10097), [#10216](https://github.com/getpaseo/paseo/pull/10216))
|
||||
- **Agent messages wait their turn:** Reports and notifications from other agents arrive in order when the current turn ends instead of interrupting it. An interrupt or your own prompt carries earlier queued messages in the same turn, and Stop holds queued messages until the next prompt instead of starting a new turn. ([#9757](https://github.com/getpaseo/paseo/pull/9757), [#10404](https://github.com/getpaseo/paseo/pull/10404))
|
||||
- **Antigravity approvals and history:** Choose a permission mode, respond to tool approvals, and import or reopen sessions. Use Antigravity CLI 1.5.0 or later on the daemon host, and include `acp` if you override its command. In Hub, reselect the model and thinking level if a saved model ID includes an old effort suffix. ([#10193](https://github.com/getpaseo/paseo/pull/10193))
|
||||
- **More goose models:** Select models from all providers configured in goose. Existing goose settings and sessions carry over to the bundled plugin. ([#9719](https://github.com/getpaseo/paseo/pull/9719) by [@i386](https://github.com/i386))
|
||||
- **Agent messages wait their turn:** By default, messages from other agents wait for the current turn to end. ([#9757](https://github.com/getpaseo/paseo/pull/9757), [#10404](https://github.com/getpaseo/paseo/pull/10404))
|
||||
- **More goose models:** Select models from every provider configured in goose. ([#9719](https://github.com/getpaseo/paseo/pull/9719) by [@i386](https://github.com/i386))
|
||||
- **Plugin agent instructions:** Plugins can add their own instructions to agents. ([#9781](https://github.com/getpaseo/paseo/pull/9781))
|
||||
|
||||
### Added
|
||||
|
||||
- Added OpenRouter credit balances and API key spending to Usage and `paseo usage` ([#10269](https://github.com/getpaseo/paseo/pull/10269))
|
||||
- Added Antigravity account quotas to Usage ([#10232](https://github.com/getpaseo/paseo/pull/10232) by [@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
- Added Antigravity skill suggestions when you type `/` inside a prompt ([#10383](https://github.com/getpaseo/paseo/pull/10383))
|
||||
- Added bundled orchestration skills to Antigravity on hosts where Paseo skills are installed ([#10273](https://github.com/getpaseo/paseo/pull/10273))
|
||||
- Added Antigravity skills to `/` suggestions ([#10383](https://github.com/getpaseo/paseo/pull/10383))
|
||||
- Added bundled orchestration skills to Antigravity ([#10273](https://github.com/getpaseo/paseo/pull/10273))
|
||||
- Added shortcuts to open the model picker and cycle thinking levels with Cmd/Ctrl+/ and Cmd/Ctrl+Shift+/ ([#10147](https://github.com/getpaseo/paseo/pull/10147))
|
||||
- Added agent settings to Command Center search before the first message ([#10182](https://github.com/getpaseo/paseo/pull/10182) by [@cleiter](https://github.com/cleiter))
|
||||
- Added Rewind to Command Center for the latest turn ([#10144](https://github.com/getpaseo/paseo/pull/10144))
|
||||
- Added a separate Ultracode toggle for eligible Claude models ([#10150](https://github.com/getpaseo/paseo/pull/10150) by [@fivetaku](https://github.com/fivetaku))
|
||||
- Added a separate Ultracode toggle for Claude ([#10150](https://github.com/getpaseo/paseo/pull/10150) by [@fivetaku](https://github.com/fivetaku))
|
||||
- Added Flex speed for Codex ([#9809](https://github.com/getpaseo/paseo/pull/9809) by [@qjqqyy](https://github.com/qjqqyy))
|
||||
- Added syntax highlighting for shell scripts and Dockerfiles ([#10178](https://github.com/getpaseo/paseo/pull/10178))
|
||||
- Added project listing on connected daemons for Hub sessions with `hub.execute` ([#10392](https://github.com/getpaseo/paseo/pull/10392))
|
||||
- Added project listing on connected daemons for Hub sessions ([#10392](https://github.com/getpaseo/paseo/pull/10392))
|
||||
- Added labels and workspace IDs to `paseo ls --json` ([#10076](https://github.com/getpaseo/paseo/pull/10076))
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed Appearance content width to Default (820 px), Wide (1,200 px), and Full presets that resize open chats, the composer, and Markdown previews together ([#10231](https://github.com/getpaseo/paseo/pull/10231))
|
||||
- Changed Antigravity tool cards to show shell commands and output, file diffs, and Paseo tool details ([#10379](https://github.com/getpaseo/paseo/pull/10379))
|
||||
- Changed content width to Default, Wide, and Full presets that also resize open chats and Markdown previews ([#10231](https://github.com/getpaseo/paseo/pull/10231))
|
||||
- Changed Antigravity tool cards to show shell commands, output, and file diffs ([#10379](https://github.com/getpaseo/paseo/pull/10379))
|
||||
- Changed Clone from GitHub to show matching private repositories first ([#10264](https://github.com/getpaseo/paseo/pull/10264))
|
||||
- Changed worktree teardown to keep the worktree when the command exceeds one minute or the `worktree.teardownTimeoutMs` limit in `paseo.json` ([#9852](https://github.com/getpaseo/paseo/pull/9852) by [@ragokan](https://github.com/ragokan))
|
||||
- Changed workspace navigation to acknowledge taps promptly and initially load fewer offscreen chat rows on mobile ([#9887](https://github.com/getpaseo/paseo/pull/9887))
|
||||
- Changed workspace Git status to reuse its snapshot after a short reconnect when the checkout has not changed ([#10142](https://github.com/getpaseo/paseo/pull/10142) by [@VladimirGVP](https://github.com/VladimirGVP))
|
||||
- Changed healthy quota bars in Usage to green ([#10397](https://github.com/getpaseo/paseo/pull/10397))
|
||||
- Changed worktree teardown to keep the worktree when the command times out ([#9852](https://github.com/getpaseo/paseo/pull/9852) by [@ragokan](https://github.com/ragokan))
|
||||
- Changed workspace navigation on mobile to acknowledge taps sooner ([#9887](https://github.com/getpaseo/paseo/pull/9887))
|
||||
- Changed workspace Git status to skip its reload after a short reconnect with no file changes ([#10142](https://github.com/getpaseo/paseo/pull/10142) by [@VladimirGVP](https://github.com/VladimirGVP))
|
||||
- Changed `browser_new_tab` to ask agents to choose a Desktop when several are connected ([#10189](https://github.com/getpaseo/paseo/pull/10189))
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed an online host's workspaces staying missing after the app evicts its cached directory ([#10318](https://github.com/getpaseo/paseo/pull/10318))
|
||||
- Fixed chat history timing out when many open chats refresh at once after reconnecting ([#10368](https://github.com/getpaseo/paseo/pull/10368))
|
||||
- Fixed an online host's workspaces going missing ([#10318](https://github.com/getpaseo/paseo/pull/10318))
|
||||
- Fixed chat history timing out when many open chats refresh after reconnecting ([#10368](https://github.com/getpaseo/paseo/pull/10368))
|
||||
- Fixed slow reopening of long Claude chats while the daemon is busy ([#10369](https://github.com/getpaseo/paseo/pull/10369))
|
||||
- Fixed images from a live reply waiting for images in another chat's history to load ([#10371](https://github.com/getpaseo/paseo/pull/10371))
|
||||
- Fixed agent recovery failing and idle agents showing errors after stopping a foreground daemon with Ctrl+C on macOS or Linux ([#10381](https://github.com/getpaseo/paseo/pull/10381))
|
||||
- Fixed reopening a long Antigravity chat after a daemon restart losing the end of its history ([#10428](https://github.com/getpaseo/paseo/pull/10428))
|
||||
- Fixed agents failing to recover after stopping a foreground daemon with Ctrl+C ([#10381](https://github.com/getpaseo/paseo/pull/10381))
|
||||
- Fixed long Antigravity chats losing the end of their history after a daemon restart ([#10428](https://github.com/getpaseo/paseo/pull/10428))
|
||||
- Fixed Antigravity turns ending while a background command is still running ([#10310](https://github.com/getpaseo/paseo/pull/10310))
|
||||
- Fixed the Add model sheet staying open after saving a custom model when provider discovery is slow or fails ([#10432](https://github.com/getpaseo/paseo/pull/10432))
|
||||
- Fixed the Add model sheet staying open after saving a custom model ([#10432](https://github.com/getpaseo/paseo/pull/10432))
|
||||
- Fixed slash suggestions failing when a provider reports duplicate command names ([#10275](https://github.com/getpaseo/paseo/pull/10275))
|
||||
- Fixed resumed Codex sessions keeping their previous working directory for configuration and MCP servers when opened in a different directory ([#10390](https://github.com/getpaseo/paseo/pull/10390) by [@tabulius-ux](https://github.com/tabulius-ux))
|
||||
- Fixed resumed Codex sessions using their previous working directory for configuration and MCP servers ([#10390](https://github.com/getpaseo/paseo/pull/10390) by [@tabulius-ux](https://github.com/tabulius-ux))
|
||||
- Fixed stale Codex subagent statuses after reopening or rewinding the parent chat ([#10171](https://github.com/getpaseo/paseo/pull/10171) by [@AnalyticETH](https://github.com/AnalyticETH))
|
||||
- Fixed Usage showing the previous Claude account's quota after switching accounts ([#10236](https://github.com/getpaseo/paseo/pull/10236))
|
||||
- Fixed the sidebar usage row dropping period labels such as `5h` and `wk` when multiple usage windows are pinned ([#10274](https://github.com/getpaseo/paseo/pull/10274))
|
||||
- Fixed the sidebar usage row dropping period labels when several usage windows are pinned ([#10274](https://github.com/getpaseo/paseo/pull/10274))
|
||||
- Fixed Changes failing to recognize a checkout immediately after restoring its worktree ([#10224](https://github.com/getpaseo/paseo/pull/10224), [#10304](https://github.com/getpaseo/paseo/pull/10304), [#10406](https://github.com/getpaseo/paseo/pull/10406))
|
||||
- Fixed split-pane dividers stopping or lagging during drags after adding panes to a previously resized row ([#5996](https://github.com/getpaseo/paseo/pull/5996))
|
||||
- Fixed split-pane dividers stopping or lagging during drags ([#5996](https://github.com/getpaseo/paseo/pull/5996))
|
||||
- Fixed double-click word selection and triple-click line selection in diffs ([#10252](https://github.com/getpaseo/paseo/pull/10252) by [@pedrovieira](https://github.com/pedrovieira))
|
||||
- Fixed the composer and chat column losing alignment when Chat outline is enabled ([#10277](https://github.com/getpaseo/paseo/pull/10277))
|
||||
- Fixed the web composer focus shortcut hint overlapping the placeholder text at narrow widths or in longer translations ([#6200](https://github.com/getpaseo/paseo/pull/6200))
|
||||
- Fixed the web composer's focus shortcut hint overlapping the placeholder ([#6200](https://github.com/getpaseo/paseo/pull/6200))
|
||||
- Fixed the archive shortcut failing when the active workspace's sidebar group is collapsed ([#10356](https://github.com/getpaseo/paseo/pull/10356) by [@hiennd-ctrl](https://github.com/hiennd-ctrl), [@neihyud](https://github.com/neihyud))
|
||||
- Fixed other sessions and plugins seeing a workspace as active while another session is archiving it ([#10391](https://github.com/getpaseo/paseo/pull/10391) by [@tabulius-ux](https://github.com/tabulius-ux))
|
||||
- Fixed Android composer buttons requiring a second tap after typing or zooming a chat image ([#10057](https://github.com/getpaseo/paseo/pull/10057), [#10308](https://github.com/getpaseo/paseo/pull/10308))
|
||||
- Fixed swiping a terminal in an Android browser opening the keyboard when it was closed ([#10225](https://github.com/getpaseo/paseo/pull/10225) by [@tonylt](https://github.com/tonylt))
|
||||
- Fixed swiping a terminal in an Android browser opening the keyboard ([#10225](https://github.com/getpaseo/paseo/pull/10225) by [@tonylt](https://github.com/tonylt))
|
||||
- Fixed Collapse turns hiding a finished OMP or Pi reply when an idle provider notice appears ([#10135](https://github.com/getpaseo/paseo/pull/10135))
|
||||
- Fixed repeated finish notifications while an agent responds to background tasks and its earlier finish is unread ([#10200](https://github.com/getpaseo/paseo/pull/10200))
|
||||
- Fixed repeated finish notifications while an agent responds to background tasks ([#10200](https://github.com/getpaseo/paseo/pull/10200))
|
||||
- Fixed an empty chat losing the prompt and start of a reply after reconnecting mid-reply ([#9723](https://github.com/getpaseo/paseo/pull/9723) by [@ragokan](https://github.com/ragokan))
|
||||
- Fixed changes between Claude thinking levels stopping its background work ([#10008](https://github.com/getpaseo/paseo/pull/10008) by [@gilad-rubin](https://github.com/gilad-rubin))
|
||||
- Fixed changing the Claude thinking level stopping its background work ([#10008](https://github.com/getpaseo/paseo/pull/10008) by [@gilad-rubin](https://github.com/gilad-rubin))
|
||||
- Fixed OpenCode turns staying running after a shared OpenCode service stops ([#10187](https://github.com/getpaseo/paseo/pull/10187))
|
||||
- Fixed OMP denying an approved tool call when session or grant choices were offered ([#10126](https://github.com/getpaseo/paseo/pull/10126) by [@dsingal0](https://github.com/dsingal0))
|
||||
- Fixed a Codex message stopped before its turn starts showing an error instead of canceled ([#9931](https://github.com/getpaseo/paseo/pull/9931) by [@3ae3ae](https://github.com/3ae3ae))
|
||||
- Fixed Changes failing to open when Git metadata watching reaches its limit ([#10188](https://github.com/getpaseo/paseo/pull/10188))
|
||||
- Fixed copying selected reply text into plain-text targets with unwanted Markdown syntax ([#10079](https://github.com/getpaseo/paseo/pull/10079) by [@danberindei](https://github.com/danberindei))
|
||||
- Fixed file views losing their scroll position when switching Preview and Source, except HTML previews on iOS ([#10195](https://github.com/getpaseo/paseo/pull/10195) by [@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- Fixed Markdown previews and source views losing their scroll position when switching between them ([#10195](https://github.com/getpaseo/paseo/pull/10195) by [@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- Fixed file tabs in split panes showing or focusing the wrong file ([#9888](https://github.com/getpaseo/paseo/pull/9888) by [@KosmoCHE](https://github.com/KosmoCHE))
|
||||
- Fixed touch-screen submenus closing as soon as they open ([#10175](https://github.com/getpaseo/paseo/pull/10175) by [@christiantwu](https://github.com/christiantwu))
|
||||
- Fixed dictation failing after another chat that used the microphone closes ([#10185](https://github.com/getpaseo/paseo/pull/10185) by [@Brandon168](https://github.com/Brandon168))
|
||||
@@ -80,13 +81,14 @@
|
||||
- Fixed Mermaid flowcharts with `@` in labels showing source instead of the diagram ([#10165](https://github.com/getpaseo/paseo/pull/10165) by [@monarchmaisuriya](https://github.com/monarchmaisuriya))
|
||||
- Fixed hidden background workspaces triggering the dock badge and favicon ([#9983](https://github.com/getpaseo/paseo/pull/9983))
|
||||
- Fixed desktop sidebar navigation crowding out workspaces ([#9903](https://github.com/getpaseo/paseo/pull/9903) by [@pentatonic-alex](https://github.com/pentatonic-alex))
|
||||
- Fixed historical closed PR badges appearing on a repository's default branch ([#10053](https://github.com/getpaseo/paseo/pull/10053))
|
||||
- Fixed closed PR badges appearing on a repository's default branch ([#10053](https://github.com/getpaseo/paseo/pull/10053))
|
||||
- Fixed plugin agents failing to reopen after their provider closes the session ([#10153](https://github.com/getpaseo/paseo/pull/10153))
|
||||
- Fixed plugin screens and settings failing to use plugin state hooks ([#10049](https://github.com/getpaseo/paseo/pull/10049))
|
||||
|
||||
### Plugins
|
||||
|
||||
- Added a `focusHost` navigation option for plugins to select the destination host in the sidebar when opening a workspace or agent ([#5574](https://github.com/getpaseo/paseo/pull/5574) by [@discwl](https://github.com/discwl))
|
||||
- Added plugin control of worktree creation, removal, and restoration ([#10278](https://github.com/getpaseo/paseo/pull/10278))
|
||||
- Added a `focusHost` navigation option that selects the destination host in the sidebar ([#5574](https://github.com/getpaseo/paseo/pull/5574) by [@discwl](https://github.com/discwl))
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
|
||||
+31
-29
@@ -2,67 +2,68 @@
|
||||
|
||||
## 0.17.1 - 2026-11-21
|
||||
|
||||
- **使用现有 worktree**:在已有的 worktree 中启动工作区,或从分支或 PR 创建 worktree。插件可以管理 worktree 的创建、移除和恢复。从 fork 的 PR 或 MR 创建分支时,选择“运行设置”以批准工作区自动化。([#10190](https://github.com/getpaseo/paseo/pull/10190), [#10278](https://github.com/getpaseo/paseo/pull/10278))
|
||||
- **在 Paseo 中更新 Provider**:在 Provider 列表中查看各 Provider 的状态、已安装版本和可用更新。从设置、初次配置或模型选择器打开 Provider 设置,即可更新受支持的 CLI 并查看输出。([#9568](https://github.com/getpaseo/paseo/pull/9568), [#9661](https://github.com/getpaseo/paseo/pull/9661))
|
||||
- **Provider 配额预测**:“使用情况”页面会根据当前使用速度估算配额在重置前何时用完,并显示在重置时间同一行中。健康的配额进度条现已改为绿色,重置与用尽时间也会在需要时显示星期和具体日期。([#10289](https://github.com/getpaseo/paseo/pull/10289), [#10385](https://github.com/getpaseo/paseo/pull/10385), [#10397](https://github.com/getpaseo/paseo/pull/10397))
|
||||
- **监视 PR 和 MR**:让 Agent 监视 GitHub、GitLab、Gitea、Forgejo 或 Codeberg 上的 PR 或 MR,跟踪检查、审查或评论的变化。你可以在后台任务中停止监视。([#10148](https://github.com/getpaseo/paseo/pull/10148), [#10279](https://github.com/getpaseo/paseo/pull/10279), [#10280](https://github.com/getpaseo/paseo/pull/10280))
|
||||
- **Antigravity 审批和历史记录**:选择权限模式、回复工具审批,以及导入或重新打开会话。需要 [Antigravity CLI 1.5.0 或更高版本](https://paseo.sh/zh-CN/docs/supported-providers/antigravity)。([#10193](https://github.com/getpaseo/paseo/pull/10193))
|
||||
- **使用现有 worktree**:在已有的 worktree 中启动工作区,或从分支或 PR 创建 worktree。([#10190](https://github.com/getpaseo/paseo/pull/10190))
|
||||
- **在 Paseo 中更新 Provider**:查看各 Provider 的状态和已安装版本,并在应用内更新受支持的 CLI。([#9568](https://github.com/getpaseo/paseo/pull/9568), [#9661](https://github.com/getpaseo/paseo/pull/9661))
|
||||
- **Provider 配额预测**:“使用情况”页面会显示配额按当前使用速度将在重置前何时用完。([#10289](https://github.com/getpaseo/paseo/pull/10289), [#10385](https://github.com/getpaseo/paseo/pull/10385))
|
||||
- **监视 PR 和 MR**:让 Agent 监视 PR 或 MR 的检查、审查和评论更新。([#10148](https://github.com/getpaseo/paseo/pull/10148), [#10279](https://github.com/getpaseo/paseo/pull/10279), [#10280](https://github.com/getpaseo/paseo/pull/10280))
|
||||
- **在后台任务中查看 heartbeat**:在 Agent 的后台任务旁查看和停止 heartbeat。([#10097](https://github.com/getpaseo/paseo/pull/10097), [#10216](https://github.com/getpaseo/paseo/pull/10216))
|
||||
- **Agent 消息排队等待**:其他 Agent 的报告和通知会在当前轮次结束后按顺序到达,不再打断当前轮次。中断消息或你发送的新提示词会在同一轮次中一并带入此前排队的其他消息;点击“停止”则会暂存排队中的消息直到下一次提示词,而不会开启新轮次。([#9757](https://github.com/getpaseo/paseo/pull/9757), [#10404](https://github.com/getpaseo/paseo/pull/10404))
|
||||
- **Antigravity 审批和历史记录**:选择权限模式、回复工具审批,以及导入或重新打开会话。请在 daemon 主机上使用 Antigravity CLI 1.5.0 或更新版本,如果覆盖了启动命令请包含 `acp`。如果 Hub 中保存的模型 ID 含有旧的推理强度后缀,请重新选择模型和思考级别。([#10193](https://github.com/getpaseo/paseo/pull/10193))
|
||||
- **更多 goose 模型**:从 goose 中已配置的所有 Provider 选择模型。现有 goose 设置和会话会迁移到内置插件。([#9719](https://github.com/getpaseo/paseo/pull/9719),贡献者:[@i386](https://github.com/i386))
|
||||
- **Agent 消息排队等待**:默认情况下,其他 Agent 的消息会等当前轮次结束后再送达。([#9757](https://github.com/getpaseo/paseo/pull/9757), [#10404](https://github.com/getpaseo/paseo/pull/10404))
|
||||
- **更多 goose 模型**:从 goose 中已配置的所有 Provider 选择模型。([#9719](https://github.com/getpaseo/paseo/pull/9719),贡献者:[@i386](https://github.com/i386))
|
||||
- **插件 Agent 指令**:插件可以向 Agent 添加自己的指令。([#9781](https://github.com/getpaseo/paseo/pull/9781))
|
||||
|
||||
### 新增
|
||||
|
||||
- 在“使用情况”页面和 `paseo usage` 中新增 OpenRouter 余额和 API 密钥支出 ([#10269](https://github.com/getpaseo/paseo/pull/10269))
|
||||
- 在“使用情况”页面新增 Antigravity 账号配额 ([#10232](https://github.com/getpaseo/paseo/pull/10232),贡献者:[@luoph](https://github.com/luoph), [@RRD-dev](https://github.com/RRD-dev))
|
||||
- 在提示词中输入 `/` 时,新增 Antigravity 技能建议 ([#10383](https://github.com/getpaseo/paseo/pull/10383))
|
||||
- 在已安装 Paseo 技能的主机上,为 Antigravity 新增内置编排技能 ([#10273](https://github.com/getpaseo/paseo/pull/10273))
|
||||
- 在 `/` 建议中新增 Antigravity 技能 ([#10383](https://github.com/getpaseo/paseo/pull/10383))
|
||||
- 为 Antigravity 新增内置编排技能 ([#10273](https://github.com/getpaseo/paseo/pull/10273))
|
||||
- 新增 Cmd/Ctrl+/ 和 Cmd/Ctrl+Shift+/ 快捷键,用于打开模型选择器和切换思考级别 ([#10147](https://github.com/getpaseo/paseo/pull/10147))
|
||||
- 新增在发送第一条消息前通过命令中心搜索 Agent 设置 ([#10182](https://github.com/getpaseo/paseo/pull/10182),贡献者:[@cleiter](https://github.com/cleiter))
|
||||
- 新增在命令中心回退最近轮次的操作 ([#10144](https://github.com/getpaseo/paseo/pull/10144))
|
||||
- 新增符合条件的 Claude 模型的独立 Ultracode 开关 ([#10150](https://github.com/getpaseo/paseo/pull/10150),贡献者:[@fivetaku](https://github.com/fivetaku))
|
||||
- 新增 Claude 的独立 Ultracode 开关 ([#10150](https://github.com/getpaseo/paseo/pull/10150),贡献者:[@fivetaku](https://github.com/fivetaku))
|
||||
- 新增 Codex Flex 速度选项 ([#9809](https://github.com/getpaseo/paseo/pull/9809),贡献者:[@qjqqyy](https://github.com/qjqqyy))
|
||||
- 新增 shell 脚本和 Dockerfile 的语法高亮 ([#10178](https://github.com/getpaseo/paseo/pull/10178))
|
||||
- 为具有 `hub.execute` 权限的 Hub 会话新增列出已连接 daemon 活跃项目的能力 ([#10392](https://github.com/getpaseo/paseo/pull/10392))
|
||||
- 为 Hub 会话新增列出已连接 daemon 项目的能力 ([#10392](https://github.com/getpaseo/paseo/pull/10392))
|
||||
- 新增 `paseo ls --json` 输出的标签和工作区 ID ([#10076](https://github.com/getpaseo/paseo/pull/10076))
|
||||
|
||||
### 变更
|
||||
|
||||
- 将“外观”中的内容宽度改为默认(820 px)、宽版(1,200 px)和全宽预设,同时调整已打开对话、Composer 和 Markdown 预览的宽度 ([#10231](https://github.com/getpaseo/paseo/pull/10231))
|
||||
- Antigravity 工具卡片现在显示 shell 命令及输出、文件 diff 和 Paseo 工具详情 ([#10379](https://github.com/getpaseo/paseo/pull/10379))
|
||||
- 将内容宽度改为默认、宽版和全宽预设,并同时调整已打开对话和 Markdown 预览的宽度 ([#10231](https://github.com/getpaseo/paseo/pull/10231))
|
||||
- Antigravity 工具卡片现在显示 shell 命令、输出和文件 diff ([#10379](https://github.com/getpaseo/paseo/pull/10379))
|
||||
- 从 GitHub 克隆时,优先显示匹配的私有仓库 ([#10264](https://github.com/getpaseo/paseo/pull/10264))
|
||||
- worktree 清理命令在超过默认的一分钟或 `paseo.json` 中 `worktree.teardownTimeoutMs` 限制时保留 worktree ([#9852](https://github.com/getpaseo/paseo/pull/9852),贡献者:[@ragokan](https://github.com/ragokan))
|
||||
- 工作区导航会立即响应点击,并在手机端初始加载时减少屏幕外的对话行数 ([#9887](https://github.com/getpaseo/paseo/pull/9887))
|
||||
- 工作区 Git 状态在短暂重连且检出的内容未更改时复用之前的快照 ([#10142](https://github.com/getpaseo/paseo/pull/10142),贡献者:[@VladimirGVP](https://github.com/VladimirGVP))
|
||||
- “使用情况”页面中健康的配额进度条改为绿色 ([#10397](https://github.com/getpaseo/paseo/pull/10397))
|
||||
- worktree 清理命令超时时保留 worktree ([#9852](https://github.com/getpaseo/paseo/pull/9852),贡献者:[@ragokan](https://github.com/ragokan))
|
||||
- 手机端工作区导航更快响应点击 ([#9887](https://github.com/getpaseo/paseo/pull/9887))
|
||||
- 短暂重连且文件未更改时,工作区 Git 状态不再重新加载 ([#10142](https://github.com/getpaseo/paseo/pull/10142),贡献者:[@VladimirGVP](https://github.com/VladimirGVP))
|
||||
- 连接多个 Desktop 时,`browser_new_tab` 会让 Agent 选择打开标签页的 Desktop ([#10189](https://github.com/getpaseo/paseo/pull/10189))
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复应用清除主机目录缓存后,在线主机的工作区一直不显示的问题 ([#10318](https://github.com/getpaseo/paseo/pull/10318))
|
||||
- 修复在线主机的工作区不显示的问题 ([#10318](https://github.com/getpaseo/paseo/pull/10318))
|
||||
- 修复重新连接后多个已打开的对话同时刷新时,历史记录加载超时的问题 ([#10368](https://github.com/getpaseo/paseo/pull/10368))
|
||||
- 修复 daemon 繁忙时,重新打开较长的 Claude 对话速度慢的问题 ([#10369](https://github.com/getpaseo/paseo/pull/10369))
|
||||
- 修复当前回复中的图片等待另一个对话的历史图片加载的问题 ([#10371](https://github.com/getpaseo/paseo/pull/10371))
|
||||
- 修复在 macOS 或 Linux 上用 Ctrl+C 停止前台 daemon 后,Agent 恢复失败且空闲 Agent 显示错误的问题 ([#10381](https://github.com/getpaseo/paseo/pull/10381))
|
||||
- 修复 daemon 重启后重新打开较长的 Antigravity 对话时丢失末尾历史记录的问题 ([#10428](https://github.com/getpaseo/paseo/pull/10428))
|
||||
- 修复用 Ctrl+C 停止前台 daemon 后 Agent 恢复失败的问题 ([#10381](https://github.com/getpaseo/paseo/pull/10381))
|
||||
- 修复 daemon 重启后较长的 Antigravity 对话丢失末尾历史记录的问题 ([#10428](https://github.com/getpaseo/paseo/pull/10428))
|
||||
- 修复 Antigravity 后台命令仍在运行时轮次就已结束的问题 ([#10310](https://github.com/getpaseo/paseo/pull/10310))
|
||||
- 修复保存自定义模型后,在 Provider 发现较慢或失败时“添加模型”弹窗一直保持打开的问题 ([#10432](https://github.com/getpaseo/paseo/pull/10432))
|
||||
- 修复保存自定义模型后“添加模型”弹窗一直保持打开的问题 ([#10432](https://github.com/getpaseo/paseo/pull/10432))
|
||||
- 修复 Provider 返回重复命令名称时,斜杠建议列表出错的问题 ([#10275](https://github.com/getpaseo/paseo/pull/10275))
|
||||
- 修复在不同目录中恢复 Codex 会话时,配置和 MCP 服务器仍沿用旧工作目录的问题 ([#10390](https://github.com/getpaseo/paseo/pull/10390),贡献者:[@tabulius-ux](https://github.com/tabulius-ux))
|
||||
- 修复恢复的 Codex 会话的配置和 MCP 服务器仍沿用旧工作目录的问题 ([#10390](https://github.com/getpaseo/paseo/pull/10390),贡献者:[@tabulius-ux](https://github.com/tabulius-ux))
|
||||
- 修复重新打开或回退父对话后,Codex 子 Agent 状态未更新的问题 ([#10171](https://github.com/getpaseo/paseo/pull/10171),贡献者:[@AnalyticETH](https://github.com/AnalyticETH))
|
||||
- 修复切换 Claude 账号后,“使用情况”页面仍显示上一个账号配额的问题 ([#10236](https://github.com/getpaseo/paseo/pull/10236))
|
||||
- 修复固定多个用量窗口时,侧边栏用量行隐藏 `5h` 和 `wk` 等周期标签的问题 ([#10274](https://github.com/getpaseo/paseo/pull/10274))
|
||||
- 修复固定多个用量窗口时,侧边栏用量行隐藏周期标签的问题 ([#10274](https://github.com/getpaseo/paseo/pull/10274))
|
||||
- 修复恢复 worktree 后,“更改”无法立即识别检出目录的问题 ([#10224](https://github.com/getpaseo/paseo/pull/10224), [#10304](https://github.com/getpaseo/paseo/pull/10304), [#10406](https://github.com/getpaseo/paseo/pull/10406))
|
||||
- 修复向调整过宽度的分屏行添加新窗格后,分隔条无法拖动或跟手缓慢的问题 ([#5996](https://github.com/getpaseo/paseo/pull/5996))
|
||||
- 修复拖动分屏分隔条时卡住或跟手缓慢的问题 ([#5996](https://github.com/getpaseo/paseo/pull/5996))
|
||||
- 修复 diff 中双击选词和三击选行的问题 ([#10252](https://github.com/getpaseo/paseo/pull/10252),贡献者:[@pedrovieira](https://github.com/pedrovieira))
|
||||
- 修复启用聊天大纲时,Composer 与对话栏对不齐的问题 ([#10277](https://github.com/getpaseo/paseo/pull/10277))
|
||||
- 修复网页版 Composer 在较窄宽度或较长译文下聚焦快捷键提示遮挡占位符文字的问题 ([#6200](https://github.com/getpaseo/paseo/pull/6200))
|
||||
- 修复网页版 Composer 的聚焦快捷键提示遮挡占位符文字的问题 ([#6200](https://github.com/getpaseo/paseo/pull/6200))
|
||||
- 修复当前工作区所在的侧边栏分组折叠时,归档快捷键失效的问题 ([#10356](https://github.com/getpaseo/paseo/pull/10356),贡献者:[@hiennd-ctrl](https://github.com/hiennd-ctrl), [@neihyud](https://github.com/neihyud))
|
||||
- 修复一个会话正在归档工作区时,其他会话和插件仍将其显示为活跃状态的问题 ([#10391](https://github.com/getpaseo/paseo/pull/10391),贡献者:[@tabulius-ux](https://github.com/tabulius-ux))
|
||||
- 修复在 Android 上输入文字或缩放对话图片后,首次点击 Composer 按钮无效的问题 ([#10057](https://github.com/getpaseo/paseo/pull/10057), [#10308](https://github.com/getpaseo/paseo/pull/10308))
|
||||
- 修复在 Android 浏览器中滑动终端时弹出已关闭的键盘的问题 ([#10225](https://github.com/getpaseo/paseo/pull/10225),贡献者:[@tonylt](https://github.com/tonylt))
|
||||
- 修复在 Android 浏览器中滑动终端时弹出键盘的问题 ([#10225](https://github.com/getpaseo/paseo/pull/10225),贡献者:[@tonylt](https://github.com/tonylt))
|
||||
- 修复启用“折叠轮次”时,空闲的 Provider 通知导致已完成的 OMP 或 Pi 回复被隐藏的问题 ([#10135](https://github.com/getpaseo/paseo/pull/10135))
|
||||
- 修复 Agent 响应后台任务时,在之前的完成状态未读的情况下重复发送完成通知的问题 ([#10200](https://github.com/getpaseo/paseo/pull/10200))
|
||||
- 修复 Agent 响应后台任务时重复发送完成通知的问题 ([#10200](https://github.com/getpaseo/paseo/pull/10200))
|
||||
- 修复空对话在回复中途重连后丢失提示词和回复开头的问题 ([#9723](https://github.com/getpaseo/paseo/pull/9723),贡献者:[@ragokan](https://github.com/ragokan))
|
||||
- 修复切换 Claude 思考级别时停止后台任务的问题 ([#10008](https://github.com/getpaseo/paseo/pull/10008),贡献者:[@gilad-rubin](https://github.com/gilad-rubin))
|
||||
- 修复共享 OpenCode 服务停止后轮次一直显示为运行中的问题 ([#10187](https://github.com/getpaseo/paseo/pull/10187))
|
||||
@@ -70,7 +71,7 @@
|
||||
- 修复 Codex 消息在轮次开始前停止时显示错误而非已取消的问题 ([#9931](https://github.com/getpaseo/paseo/pull/9931),贡献者:[@3ae3ae](https://github.com/3ae3ae))
|
||||
- 修复 Git 元数据监听达到上限时无法打开“更改”的问题 ([#10188](https://github.com/getpaseo/paseo/pull/10188))
|
||||
- 修复将选中的回复复制到纯文本目标时出现多余 Markdown 语法的问题 ([#10079](https://github.com/getpaseo/paseo/pull/10079),贡献者:[@danberindei](https://github.com/danberindei))
|
||||
- 修复在预览和源码之间切换时文件视图丢失滚动位置的问题,iOS 的 HTML 预览除外 ([#10195](https://github.com/getpaseo/paseo/pull/10195),贡献者:[@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- 修复在预览和源码之间切换时 Markdown 预览和源码视图丢失滚动位置的问题 ([#10195](https://github.com/getpaseo/paseo/pull/10195),贡献者:[@apple-ouyang](https://github.com/apple-ouyang))
|
||||
- 修复拆分窗格中的文件标签页显示或聚焦错误文件的问题 ([#9888](https://github.com/getpaseo/paseo/pull/9888),贡献者:[@KosmoCHE](https://github.com/KosmoCHE))
|
||||
- 修复触摸屏上的子菜单打开后立即关闭的问题 ([#10175](https://github.com/getpaseo/paseo/pull/10175),贡献者:[@christiantwu](https://github.com/christiantwu))
|
||||
- 修复关闭另一个使用过麦克风的对话后无法听写的问题 ([#10185](https://github.com/getpaseo/paseo/pull/10185),贡献者:[@Brandon168](https://github.com/Brandon168))
|
||||
@@ -80,13 +81,14 @@
|
||||
- 修复 Mermaid 流程图标签含有 `@` 时显示源码而非图表的问题 ([#10165](https://github.com/getpaseo/paseo/pull/10165),贡献者:[@monarchmaisuriya](https://github.com/monarchmaisuriya))
|
||||
- 修复隐藏的后台工作区触发程序坞徽标和网站图标状态的问题 ([#9983](https://github.com/getpaseo/paseo/pull/9983))
|
||||
- 修复桌面侧边栏导航占满工作区列表空间的问题 ([#9903](https://github.com/getpaseo/paseo/pull/9903),贡献者:[@pentatonic-alex](https://github.com/pentatonic-alex))
|
||||
- 修复仓库默认分支显示历史已关闭 PR 徽标的问题 ([#10053](https://github.com/getpaseo/paseo/pull/10053))
|
||||
- 修复仓库默认分支显示已关闭 PR 徽标的问题 ([#10053](https://github.com/getpaseo/paseo/pull/10053))
|
||||
- 修复 Provider 关闭会话后插件 Agent 无法重新打开的问题 ([#10153](https://github.com/getpaseo/paseo/pull/10153))
|
||||
- 修复插件页面和设置无法使用插件状态钩子的问题 ([#10049](https://github.com/getpaseo/paseo/pull/10049))
|
||||
|
||||
### 插件
|
||||
|
||||
- 新增插件导航 `focusHost` 选项,打开工作区或 Agent 时在侧边栏选中目标主机 ([#5574](https://github.com/getpaseo/paseo/pull/5574),贡献者:[@discwl](https://github.com/discwl))
|
||||
- 新增插件对 worktree 创建、移除和恢复的管理能力 ([#10278](https://github.com/getpaseo/paseo/pull/10278))
|
||||
- 新增插件导航 `focusHost` 选项,用于在侧边栏选中目标主机 ([#5574](https://github.com/getpaseo/paseo/pull/5574),贡献者:[@discwl](https://github.com/discwl))
|
||||
|
||||
## 0.16.2 - 2026-11-18
|
||||
|
||||
|
||||
@@ -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 |
|
||||
|
||||
+12
-5
@@ -152,14 +152,21 @@ Users can also detach an existing subagent from the subagents track. Detach is d
|
||||
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
|
||||
|
||||
- **`steer`** (the agent default) waits. An idle recipient gets the queue after two quiet seconds; steady arrivals cannot hold that window open past ten seconds. While the recipient has a running or starting turn (including compaction), the queue waits and is delivered together when that turn ends on its own or fails. The daemon releases it when it observes the recipient settle; a two-second timer also retries.
|
||||
- **`interrupt`** waits for neither the quiet window nor the turn. It is dispatched at admission as one prompt that replaces the running turn: the messages queued before it, then the interrupt. An older `steer` cannot start a turn after the newer `interrupt` that countermands it.
|
||||
An agent sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. `steer` and `interrupt` mean what they mean for a person. A person's send has no `queue`. Each kind of prompt is released this way:
|
||||
|
||||
- **`queue`** (the agent default) waits. An idle recipient gets the queue after two quiet seconds; steady arrivals cannot hold that window open past ten seconds. While the recipient has a running or starting turn (including compaction), the queue waits and is delivered together when that turn ends on its own or fails. The daemon releases it when it observes the recipient settle; a two-second timer also retries. Finish notifications and change-request updates always queue.
|
||||
- **`steer`** waits for neither the quiet window nor the turn. It is dispatched at admission as one prompt that enters the running turn: the messages queued before it, then the steer. A provider that cannot steer, or that refuses this steer, gets the prompt as a replacing turn instead, the same as a person's steer.
|
||||
- **`interrupt`** is dispatched at admission the same way, as one prompt that replaces the running turn. An older queued message cannot start a turn after the newer `interrupt` that countermands it.
|
||||
- **A person's prompt** (app, CLI, top-level MCP) is dispatched directly with its existing steer or interrupt behavior and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice.
|
||||
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. They go ahead of the recipient's next prompt, in that prompt's turn: a person's prompt, or an agent message or notification admitted after the Stop. A held interrupt no longer interrupts; it waits like a `steer`. A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued `steer` keeps its quiet window.
|
||||
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. They go ahead of the recipient's next prompt, in that prompt's turn: a person's prompt, or an agent message or notification admitted after the Stop. A held steer or interrupt no longer enters the turn; it waits like a queued message. A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued message keeps its quiet window.
|
||||
|
||||
A command the provider accepts out of band is the one exception to admission order: it runs alone without ending the turn. A queued command runs ahead of older messages, and an `interrupt` that runs this way takes no queued message along. A person's command leaves the queue where it is. A prompt is a command when it starts with a slash and a name that has no second slash, so `/compact` is one and `/tmp/build.log is stale` is plain text.
|
||||
The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because the follow-up carries the queued message ahead of it and a resend would be read twice. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
|
||||
|
||||
One provider prompt has one session mode. A batch released by an interrupt or a person's prompt uses the latest explicit choice in it, the person's own first. Steers with conflicting choices keep separate ordered dispatches.
|
||||
Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`.
|
||||
|
||||
A command the provider accepts out of band is the one exception to admission order: it runs alone without ending the turn. A queued command runs ahead of older messages, and a `steer` or `interrupt` that runs this way takes no queued message along. A person's command leaves the queue where it is. A prompt is a command when it starts with a slash and a name that has no second slash, so `/compact` is one and `/tmp/build.log is stale` is plain text.
|
||||
|
||||
One provider prompt has one session mode. A batch released by a steer, an interrupt, or a person's prompt uses the latest explicit choice in it, the person's own first. Queued messages with conflicting choices keep separate ordered dispatches.
|
||||
|
||||
The pending message window is in memory. Clean shutdown flushes it, held messages included, before
|
||||
closing agents; an abrupt crash can lose queued prompts. A durable send receipt remains pending until actual dispatch
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
||||
- **Agent controls** — Provider, model, mode, thinking, and provider-feature controls for an agent or draft agent. Code: `AgentControls` / `DraftAgentControls` (`packages/app/src/composer/agent-controls/index.tsx`). Forbidden: "Agent status bar".
|
||||
- **Composer footer** — Optional area rendered below the composer input but still inside the keyboard-shifted composer layout. Code: `Composer.footer` (`packages/app/src/composer/index.tsx`).
|
||||
- **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the `<thing> track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the queue track is a lane inside the composer itself. Code: queue track inside `Composer` (`packages/app/src/composer/index.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`).
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which holds messages client-side until the turn ends and never enters the running turn. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which holds messages client-side until the turn ends and never enters the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as the queue track does for a person. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Subagent** — User-facing term for an agent session related to a parent agent session. Use **subagents** in UI copy and docs. Internal daemon/provider plumbing may say "child agent" or `child_session`, especially for provider-managed imports; do not surface "child agent" as a product term.
|
||||
- **Attachment tray** — The selected-attachments row inside the composer input, above the text input. Code: `renderAttachmentTray` (`packages/app/src/composer/index.tsx`). Forbidden: "Attachment bar".
|
||||
- **Fork** — Starting a NEW agent session seeded with a copy of another session's curated chat history. The history rides along as a `chat_history` composer attachment on a draft; the fork does **not** resume or branch the provider-side session, and the source session keeps running untouched. Two targets, one surface, one RPC (`agent.fork_context`, gated on the `agentForkContext` host feature). UI: the fork menu lives in the assistant turn footer and offers "Fork in a new tab" / "Fork in a new workspace". On a **completed** turn it sits beside the copy button and pins a boundary to that turn, so the fork stops where the turn ended. On the **in-flight** turn it sits beside the progress loader and elapsed timer, and omits the boundary entirely — `selectForkContextRows` projects the whole timeline when no boundary is given, so the fork captures everything **up to now**, including the response still streaming. That omission is what makes mid-run forking work; pinning a boundary there would silently drop the live response. Forbidden on provider-subagent (read-only) panes. Code: `useForkAgent` (`packages/app/src/hooks/use-fork-agent.ts`), `selectForkContextRows` (`packages/server/src/server/agent/activity-curator.ts`). Don't confuse with: git fork (unrelated; Paseo has no such concept), **Worktree** (filesystem isolation, not history copying).
|
||||
|
||||
+3
-2
@@ -72,8 +72,9 @@ hashes, never prompts, environment values, or credentials.
|
||||
|
||||
Before messaging an archived workspace, call `workspace.recovery.inspect.request`, then
|
||||
`workspace.recovery.restore.request` and await success. The native message handler unarchives the
|
||||
agent and loads its persisted provider session. `activeTurnBehavior: "steer"` uses the provider's
|
||||
native steering behavior, including Paseo's existing behavior when that provider cannot steer.
|
||||
agent and loads its persisted provider session. A Hub message is a direct send (no `sourceAgentId`), so
|
||||
`activeTurnBehavior: "steer"` uses the provider's native steering and interrupts the running turn
|
||||
when that provider cannot steer. The daemon rejects `queue` on a direct send.
|
||||
Execution completion and arrival-specific output authority remain Hub responsibilities.
|
||||
|
||||
The older `hub.execution.*` RPCs remain accepted for existing clients. Their execution ownership
|
||||
|
||||
@@ -14,19 +14,38 @@ 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.
|
||||
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 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 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.
|
||||
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.
|
||||
|
||||
|
||||
+38
-16
@@ -659,6 +659,7 @@ No prefix (`v`), no extra text. `Release Notes Sync` matches the `## X.Y.Z` (or
|
||||
- `CHANGELOG.md` holds stable releases and at most one entry for the current beta series.
|
||||
- The first beta of a version inserts a top entry like `## 0.1.60-beta.1 - YYYY-MM-DD`.
|
||||
- Each subsequent beta rewrites that entry in place: the heading becomes the new beta number and date, and the body describes the full change from the previous stable release to this beta. Never add a second beta entry.
|
||||
- The entry announces changes and leaves setup steps, click paths, migration notes, configuration keys, hedges and edge cases to product docs. The headline change is the first highlight. [Changelog conciseness](#changelog-conciseness) and [Changelog ordering](#changelog-ordering) hold the rules.
|
||||
- The entry is a list of changes, not of PRs. When a later beta reverts, reworks, or follows up on something an earlier beta added, rewrite the bullet to the current behavior or delete it. A stable user never saw the earlier beta behavior, so fixes to it are not "Fixed" bullets.
|
||||
- Anything that already shipped to stable through a patch release on an older line stays out of the beta entry.
|
||||
- Stable promotion renames the entry to `## 0.1.60 - YYYY-MM-DD` after a final review.
|
||||
@@ -714,14 +715,30 @@ claims a general improvement, rewrite it with the concrete change.
|
||||
|
||||
## Changelog conciseness
|
||||
|
||||
Every section bullet must be scannable at a glance. The changelog is not release documentation — it's a list. [Highlights](#changelog-highlights) get more room; every other bullet follows these limits.
|
||||
An entry announces what changed. Product docs own setup, navigation, migration and edge cases, and the PR link leads to the rest. These rules apply to highlights and section bullets.
|
||||
|
||||
- **One sentence per bullet, max.** If a bullet contains two sentences, the second one is doing work that belongs in product docs, not the changelog. Cut it.
|
||||
- **No instructions.** Cut setup steps, click paths, configuration keys, flags and migration notes. "Open a provider's settings from Settings, setup, or the model picker" is a click path. "Existing goose settings and sessions carry over to the bundled plugin" is a migration note.
|
||||
- **One warning for a breaking requirement.** When the update stops something working until the user acts, state the requirement in one short sentence after the announcement, and link the product doc that has the steps: "Requires [Antigravity CLI 1.5.0 or later](https://paseo.sh/docs/supported-providers/antigravity)." Nothing else earns a second sentence.
|
||||
- **No hedges or exception clauses.** Cut "when needed", "for eligible models", "on hosts where…", "except…", "with a hint shown when…" and "across common install shapes". Keep the condition that triggers a fixed failure, as in `Fixed <failure> when <condition>`.
|
||||
- **The shorter bullet is still true.** When a change reaches only some providers, platforms or file types, name what it covers in the sentence's own words: "update supported CLIs" where one provider has no update command, "Markdown previews and source views" where HTML previews on iOS are left out, "by default" where an explicit interrupt still replaces the turn. Do not widen the claim to remove a clause.
|
||||
- **State the outcome and stop.** Say what the user gets. Leave out queues, snapshots, caches, timeouts, LAN/WAN topology, TLS handshakes and IPC.
|
||||
|
||||
Each row is from the first draft of 0.17.1:
|
||||
|
||||
| Avoid | Write |
|
||||
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
|
||||
| Open a provider's settings from Settings, setup, or the model picker to update supported CLIs and watch their output | Update supported CLIs from the app |
|
||||
| Use Antigravity CLI 1.5.0 or later on the daemon host, and include `acp` if you override its command | Requires Antigravity CLI 1.5.0 or later |
|
||||
| Reports and notifications from other agents arrive in order when the current turn ends instead of interrupting it. An interrupt or your own prompt carries earlier queued messages in the same turn, and Stop holds queued messages until the next prompt | By default, messages from other agents wait for the current turn to end |
|
||||
| Changed worktree teardown to keep the worktree when the command exceeds one minute or the `worktree.teardownTimeoutMs` limit in `paseo.json` | Changed worktree teardown to keep the worktree when the command times out |
|
||||
| Fixed file views losing their scroll position when switching Preview and Source, except HTML previews on iOS | Fixed Markdown previews and source views losing their scroll position when switching between them |
|
||||
|
||||
Section bullets also follow these limits:
|
||||
|
||||
- **One sentence per bullet, max.** A second sentence is documentation. Cut it.
|
||||
- **No trailing periods.** Bullets are list items, not prose. Drop the period at the end of every bullet, including the period inside any bolded lead-in. `**Configurable terminal scrollback**` not `**Configurable terminal scrollback.**`.
|
||||
- **One line per bullet.** If a bullet wraps to three lines in a narrow column, it's too long.
|
||||
- **Split bullets that pack multiple distinct changes.** If a bullet uses "and", "plus", a comma list, or an em-dash to chain several independent improvements, break them into separate bullets — even when they share a theme or author. One bullet = one user-facing change.
|
||||
- **Trim qualifying clauses.** Drop "with a hint shown when…", "matching the CLI's behaviour", "across common install shapes". If the detail doesn't change whether a user cares, cut it.
|
||||
- **Stop after identifying the change.** Do not explain LAN/WAN topology, TLS handshakes, IPC, or other architecture in a changelog bullet. Put necessary background in product docs.
|
||||
- **Attribution follows the split.** When you split a dense bullet, move each PR/author to the bullet it belongs to. Never duplicate the same PR across multiple bullets.
|
||||
|
||||
## Changelog highlights
|
||||
@@ -734,7 +751,7 @@ reader who stops after the highlights should have missed nothing they would ask
|
||||
```markdown
|
||||
## 0.16.0 - 2026-11-20
|
||||
|
||||
- **Undo workspace archive:** Archiving a workspace in the app now shows a "Workspace archived" toast for six seconds. Undo, or Cmd/Ctrl+Z, restores the workspace with its tabs and agents. ([#8904](https://github.com/getpaseo/paseo/pull/8904))
|
||||
- **Undo workspace archive:** Restore an archived workspace with Undo or Cmd/Ctrl+Z. ([#8904](https://github.com/getpaseo/paseo/pull/8904))
|
||||
|
||||
### Added
|
||||
```
|
||||
@@ -745,17 +762,19 @@ reader who stops after the highlights should have missed nothing they would ask
|
||||
- **The lead-in is not a place or something Paseo already had.** A device, screen or area names
|
||||
where the change landed. A feature name that was true of the last release hides the news: Paseo
|
||||
already had keyboard shortcuts, so the lead-in says they now work on mobile.
|
||||
- **The first sentence says the plain thing.** Write what a user would tell a friend: Paseo now
|
||||
- **One short sentence says the plain thing.** Write what a user would tell a friend: Paseo now
|
||||
shows the background tasks an agent is running. Leave out the conditions and mechanics that make
|
||||
it true.
|
||||
it true. A second sentence is only for a
|
||||
[breaking requirement](#changelog-conciseness).
|
||||
- **Describe the new behavior, not the old one.** Say what is faster or better now, and do not
|
||||
dwell on how slow or broken it was before. A number is welcome as a short aside after the new
|
||||
behavior is stated: seconds, a percentage, a multiple.
|
||||
- **Do not list what a sentence already covers.** After "the same shortcuts as desktop", naming
|
||||
five of them adds nothing. Keep a list only when it sets the scope, such as the providers a
|
||||
feature works with.
|
||||
- **The description runs one to three sentences.** Sentences end with periods, and the attribution
|
||||
follows the last one. [Changelog wording](#changelog-wording) applies in full.
|
||||
- **Sentences end with periods, and the attribution follows the last one.**
|
||||
[Changelog wording](#changelog-wording) and [Changelog conciseness](#changelog-conciseness)
|
||||
apply.
|
||||
- **A highlight replaces the section bullets it covers.** A PR appears once in an entry, so its
|
||||
attribution moves to the highlight.
|
||||
- **A highlight is something a user would name.** Everything else stays a section bullet. A patch
|
||||
@@ -764,13 +783,13 @@ reader who stops after the highlights should have missed nothing they would ask
|
||||
of related fixes, becomes a highlight only when it passes the same test as a feature, and then
|
||||
it is written as what works now: `**Fewer reconnects on return:**`.
|
||||
|
||||
| Avoid | Write |
|
||||
| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |
|
||||
| `**iPad and touch screens:**` | `**Touch-sized tablet controls:**` |
|
||||
| `**Hardware keyboard shortcuts:**` | `**Keyboard shortcuts on mobile:**` |
|
||||
| When an agent ends its turn while shells it started are still running, a pill lists them | Paseo now shows the background tasks an agent is running |
|
||||
| A diff no longer waits 4 to 40 seconds behind worktree scans | Opening Changes shows the file tree right away, and diffs load about 6 times sooner on hosts with many worktrees |
|
||||
| The same shortcuts as desktop: command center, file picker, new workspace, workspace jumps | The same shortcuts as desktop, including your custom bindings |
|
||||
| Avoid | Write |
|
||||
| ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
|
||||
| `**iPad and touch screens:**` | `**Touch-sized tablet controls:**` |
|
||||
| `**Hardware keyboard shortcuts:**` | `**Keyboard shortcuts on mobile:**` |
|
||||
| When an agent ends its turn while shells it started are still running, a pill lists them | Paseo now shows the background tasks an agent is running |
|
||||
| A diff no longer waits 4 to 40 seconds behind worktree scans | Opening Changes shows the file tree right away, and diffs load about 6 times sooner |
|
||||
| The same shortcuts as desktop: command center, file picker, new workspace, workspace jumps | The same shortcuts as desktop, including your custom bindings |
|
||||
|
||||
Before showing a draft, read only the bold lead-ins top to bottom. Each one must answer "what is
|
||||
new?" without its description, and each must outrank the one below it.
|
||||
@@ -820,6 +839,9 @@ question.
|
||||
for them: `Undo workspace archive`, `Fewer reconnects on return`. Fixes are routine, so one
|
||||
that earned a highlight still follows everything new or improved.
|
||||
|
||||
- **The headline change goes first, whatever its group.** It is the change the release is announced
|
||||
with. 0.17.1 leads with `Antigravity approvals and history`, which needs one provider. The groups
|
||||
rank everything after it.
|
||||
- **Reach decides before kind.** A new capability that needs a hardware keyboard is in group 3.
|
||||
- **Rank the whole list in one pass.** The order you collected the pull requests in, the alphabet
|
||||
and the order of the sections below are not rankings.
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request. Plugins can manage worktree creation, removal, and restoration. When you branch off a fork PR or MR, choose Run setup to approve workspace automation.
|
||||
- Antigravity approvals and history: Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires Antigravity CLI 1.5.0 or later.
|
||||
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request.
|
||||
- Update providers in Paseo: See each provider's status and installed version, and update supported CLIs from the app.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request. Plugins can manage worktree creation, removal, and restoration. When you branch off a fork PR or MR, choose Run setup to approve workspace automation.
|
||||
- Antigravity approvals and history: Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires Antigravity CLI 1.5.0 or later.
|
||||
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request.
|
||||
- Update providers in Paseo: See each provider's status and installed version, and update supported CLIs from the app.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request. Plugins can manage worktree creation, removal, and restoration. When you branch off a fork PR or MR, choose Run setup to approve workspace automation.
|
||||
- Antigravity approvals and history: Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires Antigravity CLI 1.5.0 or later.
|
||||
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request.
|
||||
- Update providers in Paseo: See each provider's status and installed version, and update supported CLIs from the app.
|
||||
|
||||
Full notes: https://paseo.sh/changelog
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request. Plugins can manage worktree creation, removal, and restoration. When you branch off a fork PR or MR, choose Run setup to approve workspace automation.
|
||||
- Antigravity approvals and history: Choose a permission mode, answer tool approvals, and import or reopen sessions. Requires Antigravity CLI 1.5.0 or later.
|
||||
- Use existing worktrees: Start a workspace in a worktree you already have, or create one from a branch or pull request.
|
||||
- Update providers in Paseo: See each provider's status and installed version, and update supported CLIs from the app.
|
||||
|
||||
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-esZ6cghL+VfK01yLZlFIK/M94+q0a2e+od3rvA3lPqo=
|
||||
sha256-qZCOSeT264mXP2RcV+eD7lEkc3WAH1re6NjTtbQOHqY=
|
||||
|
||||
Generated
+21
-18
@@ -12,6 +12,7 @@
|
||||
"workspaces": [
|
||||
"plugins",
|
||||
"packages/expo-two-way-audio",
|
||||
"packages/react-native-enriched-markdown",
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
@@ -31902,6 +31903,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",
|
||||
@@ -37561,7 +37566,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 +39479,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",
|
||||
@@ -40303,6 +40291,21 @@
|
||||
"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.1",
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"workspaces": [
|
||||
"plugins",
|
||||
"packages/expo-two-way-audio",
|
||||
"packages/react-native-enriched-markdown",
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
|
||||
@@ -59,6 +59,35 @@ async function selectClientSlashCommand(page: Page, query: string, label: string
|
||||
await input.press("Enter");
|
||||
}
|
||||
|
||||
async function typeBeforeMenuFilters(
|
||||
page: Page,
|
||||
input: { text: string; key: "Tab" | "Enter" },
|
||||
): Promise<void> {
|
||||
await composerLocator(page).evaluate(async (element, { text, key }) => {
|
||||
if (!(element instanceof HTMLTextAreaElement)) {
|
||||
throw new Error("Composer input is not a textarea");
|
||||
}
|
||||
const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set;
|
||||
if (!setValue) throw new Error("Textarea value setter is unavailable");
|
||||
setValue.call(element, text);
|
||||
element.setSelectionRange(text.length, text.length);
|
||||
element.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await Promise.resolve();
|
||||
element.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
|
||||
await new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve, 0)));
|
||||
}, input);
|
||||
}
|
||||
|
||||
async function showExitSuggestion(page: Page, query: string): Promise<void> {
|
||||
await composerLocator(page).fill(query);
|
||||
await expect(page.getByText("/exit", { exact: true }).first()).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectOpenAgentWithInput(page: Page, agentId: string, text: string): Promise<void> {
|
||||
await expect(composerLocator(page)).toHaveValue(text);
|
||||
await expectWorkspaceTabVisible(page, agentId);
|
||||
}
|
||||
|
||||
async function expectAgentArchivedInSessions(page: Page, title: string): Promise<void> {
|
||||
await openSessions(page);
|
||||
await expectSessionRowArchived(page, title);
|
||||
@@ -131,6 +160,16 @@ test.describe("Client slash commands", () => {
|
||||
);
|
||||
});
|
||||
|
||||
for (const key of ["Tab", "Enter"] as const) {
|
||||
test(`${key} ignores an exit suggestion for an earlier query`, async ({ page }) => {
|
||||
await withOpenReadyMockAgent(page, { title: "Stale slash command" }, async ({ agentId }) => {
|
||||
await showExitSuggestion(page, "/e");
|
||||
await typeBeforeMenuFilters(page, { text: "/co", key });
|
||||
await expectOpenAgentWithInput(page, agentId, "/co");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("slash clear replaces the active agent with a matching draft", async ({ page }) => {
|
||||
await withOpenReadyMockAgent(
|
||||
page,
|
||||
|
||||
@@ -1,4 +1,21 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { createCreationScenario } from "../support/helpers/creation";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { fillComposerDraft } from "../support/helpers/composer";
|
||||
import {
|
||||
connectNewWorkspaceDaemonClient,
|
||||
openNewWorkspaceComposer,
|
||||
selectWorkspaceIsolation,
|
||||
} from "../support/helpers/new-workspace";
|
||||
import {
|
||||
seedTerminalProfiles,
|
||||
selectLaunchOption,
|
||||
submitTerminalLaunch,
|
||||
} from "../support/helpers/new-workspace-launch";
|
||||
import { waitForSidebarHydration } from "../support/helpers/workspace-ui";
|
||||
import { expect } from "../support/fixtures";
|
||||
import { test } from "../support/creation-fixtures";
|
||||
|
||||
@@ -116,12 +133,14 @@ for (const scenario of [
|
||||
test(`retrying failed agent initialization preserves its workspace${scenario.suffix}`, async ({
|
||||
creation,
|
||||
startup,
|
||||
page,
|
||||
}) => {
|
||||
await creation.openWorkspaceForm("local");
|
||||
await creation.submitPrompt("Retry this workspace and agent together.", "Create");
|
||||
await creation.expectAgentStillStarting();
|
||||
await startup.fail();
|
||||
await creation.expectStartupFailure();
|
||||
await expect(page.getByTestId("app-toast")).toHaveCount(0);
|
||||
await creation.expectOneCreatedWorkspace();
|
||||
await scenario.prepare(creation);
|
||||
await creation.submitPrompt("Retry this workspace and agent together.");
|
||||
@@ -180,6 +199,105 @@ test("an edited agent draft starts after its first start failed", async ({
|
||||
await expect(page.getByText(/request_key_conflict/)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("editing a failed New workspace submission starts without a request key conflict", async ({
|
||||
page,
|
||||
}) => {
|
||||
// An empty git repository naturally rejects worktree creation before workspace_ready.
|
||||
const repoDir = mkdtempSync(path.join(tmpdir(), "paseo-empty-git-ws-"));
|
||||
execFileSync("git", ["init"], { cwd: repoDir, stdio: "ignore" });
|
||||
const client = await connectNewWorkspaceDaemonClient();
|
||||
let projectId: string | null = null;
|
||||
try {
|
||||
const seeded = await client.createWorkspace({
|
||||
source: { kind: "directory", path: repoDir },
|
||||
});
|
||||
if (!seeded.workspace) throw new Error(seeded.error ?? "Failed to seed empty git project");
|
||||
projectId = seeded.workspace.projectId;
|
||||
const listed = await client.listProjects();
|
||||
const project = listed.projects.find((entry) => entry.projectId === projectId);
|
||||
if (!project?.projectKey) throw new Error("Seeded project has no projectKey");
|
||||
|
||||
await gotoAppShell(page);
|
||||
await waitForSidebarHydration(page);
|
||||
await openNewWorkspaceComposer(page, {
|
||||
projectKey: project.projectKey,
|
||||
projectDisplayName: seeded.workspace.projectDisplayName,
|
||||
});
|
||||
await selectWorkspaceIsolation(page, "worktree");
|
||||
await fillComposerDraft(page, "Start original worktree task.");
|
||||
await page.getByRole("button", { name: "Create", exact: true }).click();
|
||||
|
||||
const composerError = page.getByTestId("composer-error").filter({ visible: true }).first();
|
||||
await expect(composerError).toContainText("Unable to resolve repository default branch");
|
||||
// The failure renders once in the composer alert, not duplicated in a top toast.
|
||||
await expect(page.getByText("Unable to resolve repository default branch")).toHaveCount(1);
|
||||
|
||||
await selectWorkspaceIsolation(page, "local");
|
||||
await fillComposerDraft(page, "hi");
|
||||
await page.getByRole("button", { name: "Create", exact: true }).click();
|
||||
|
||||
await expect(page).toHaveURL(/\/workspace\//);
|
||||
await expect(page.getByText(/request_key_conflict/)).toHaveCount(0);
|
||||
await expect(
|
||||
page.getByTestId("user-message").filter({ hasText: "hi", visible: true }),
|
||||
).toBeVisible();
|
||||
} finally {
|
||||
if (projectId) await client.removeProject(projectId).catch(() => undefined);
|
||||
await client.close();
|
||||
rmSync(repoDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("switching only the launch target after a failed New workspace creation starts a new workspace", async ({
|
||||
creation,
|
||||
workspaceProvision,
|
||||
page,
|
||||
}) => {
|
||||
const profiles = await seedTerminalProfiles([
|
||||
{
|
||||
id: "promptless-shell",
|
||||
name: "Promptless Shell",
|
||||
command: "sh",
|
||||
args: ["-c", "echo ready; sleep 5"],
|
||||
promptArg: "none",
|
||||
},
|
||||
]);
|
||||
try {
|
||||
await creation.openWorkspaceForm("local");
|
||||
await workspaceProvision.fail();
|
||||
await page.getByRole("button", { name: "Create", exact: true }).click();
|
||||
await expect(
|
||||
page.getByTestId("composer-error").filter({ visible: true }).first(),
|
||||
).toContainText("Workspace provisioning failed for test");
|
||||
|
||||
await selectLaunchOption(page, "promptless-shell");
|
||||
await submitTerminalLaunch(page);
|
||||
await creation.expectOneCreatedWorkspace();
|
||||
await expect(
|
||||
page.locator('[data-testid^="workspace-tab-terminal_"]').filter({ visible: true }).first(),
|
||||
).toBeVisible();
|
||||
} finally {
|
||||
await profiles.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("failing New workspace creation after switching workspaces shows an error toast", async ({
|
||||
creation,
|
||||
workspaceProvision,
|
||||
page,
|
||||
}) => {
|
||||
await creation.openWorkspaceForm("local");
|
||||
await workspaceProvision.hold();
|
||||
await page.getByRole("button", { name: "Create", exact: true }).click();
|
||||
await page.locator('[data-testid^="sidebar-workspace-row-"]').first().click();
|
||||
await expect(page).toHaveURL(/\/workspace\//);
|
||||
|
||||
await workspaceProvision.fail();
|
||||
await expect(page.getByTestId("app-toast")).toContainText(
|
||||
"Workspace provisioning failed for test",
|
||||
);
|
||||
});
|
||||
|
||||
for (const entry of [
|
||||
{
|
||||
name: "agent draft",
|
||||
|
||||
@@ -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 \
|
||||
|
||||
@@ -15,6 +15,11 @@ import { delayBrowserAgentCreatedStatus } from "./helpers/new-workspace";
|
||||
|
||||
export const test = base.extend<{
|
||||
startup: { release(): Promise<void>; fail(): Promise<void> };
|
||||
workspaceProvision: {
|
||||
hold(): Promise<void>;
|
||||
fail(): Promise<void>;
|
||||
release(): Promise<void>;
|
||||
};
|
||||
promptRejection: void;
|
||||
composerMetadata: { set(patch: Record<string, string>): Promise<void> };
|
||||
creation: Awaited<ReturnType<typeof createCreationScenario>>;
|
||||
@@ -70,6 +75,57 @@ export default function contribute(server) {
|
||||
await client.close();
|
||||
}
|
||||
},
|
||||
workspaceProvision: async ({ page }, provide) => {
|
||||
void page;
|
||||
const client = await connectNewWorkspaceDaemonClient();
|
||||
const plugin = await copyPluginExample("lifecycle-logger");
|
||||
const gate = path.join(plugin.directory, "workspace-provision.txt");
|
||||
const holdFile = path.join(plugin.directory, "workspace-provision-hold.txt");
|
||||
const failFile = path.join(plugin.directory, "workspace-provision-fail.txt");
|
||||
const previous = await client.getDaemonConfig();
|
||||
try {
|
||||
await writeFile(
|
||||
path.join(plugin.directory, "index.server.ts"),
|
||||
`
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
export default function contribute(server) {
|
||||
return server.before("workspace.create", async ({ request }) => {
|
||||
const gate = ${JSON.stringify(gate)};
|
||||
let command = await readFile(gate, "utf8").catch(() => "release");
|
||||
while (command === "hold") {
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
command = await readFile(gate, "utf8").catch(() => "release");
|
||||
}
|
||||
if (command === "fail") {
|
||||
await rm(gate, { force: true });
|
||||
throw new Error("Workspace provisioning failed for test");
|
||||
}
|
||||
return request;
|
||||
});
|
||||
}
|
||||
`,
|
||||
);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(plugin.directory);
|
||||
await provide({
|
||||
hold: async () => {
|
||||
await writeFile(holdFile, "hold");
|
||||
await rename(holdFile, gate);
|
||||
},
|
||||
fail: async () => {
|
||||
await writeFile(failFile, "fail");
|
||||
await rename(failFile, gate);
|
||||
},
|
||||
release: () => rm(gate, { force: true }),
|
||||
});
|
||||
} finally {
|
||||
await rm(gate, { force: true });
|
||||
await client.removePlugin("lifecycle-logger");
|
||||
await client.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled });
|
||||
await plugin.cleanup();
|
||||
await client.close();
|
||||
}
|
||||
},
|
||||
promptRejection: async ({ page }, provide) => {
|
||||
void page;
|
||||
const client = await connectNewWorkspaceDaemonClient();
|
||||
|
||||
@@ -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' --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",
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Composer } from "@/composer";
|
||||
import { ProjectIconView } from "@/components/project-icon-view";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { draftCreationKey } from "@/composer/draft/creation-key";
|
||||
import { useAgentInputDraft } from "@/composer/draft/input-draft";
|
||||
import { useProjectIcon } from "@/projects/icons";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
@@ -96,13 +97,16 @@ async function callWorkspaceCreation({
|
||||
worktreeSlug: string;
|
||||
input: { cwd: string; agent?: CreateWorkspaceRequestOptions["agent"] };
|
||||
}) {
|
||||
return connectedClient.createWorkspace({
|
||||
idempotencyKey: creationId,
|
||||
const request: Omit<CreateWorkspaceRequestOptions, "idempotencyKey"> = {
|
||||
agent: input.agent,
|
||||
source:
|
||||
creationMethod === "create_worktree"
|
||||
? { kind: "worktree", cwd: input.cwd, worktreeSlug }
|
||||
: { kind: "directory", path: input.cwd },
|
||||
};
|
||||
return connectedClient.createWorkspace({
|
||||
...request,
|
||||
idempotencyKey: draftCreationKey(creationId, request),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -363,7 +367,9 @@ export function WorkspaceSetupDialog() {
|
||||
} catch (error) {
|
||||
const message = toErrorMessage(error);
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
if (!getIsStillActive()) {
|
||||
toast.error(message);
|
||||
}
|
||||
} finally {
|
||||
if (getIsStillActive()) {
|
||||
setPendingAction(null);
|
||||
@@ -455,11 +461,10 @@ export function WorkspaceSetupDialog() {
|
||||
commandDraft={composerState?.commandDraft}
|
||||
agentControls={agentControlsWithDisabled}
|
||||
inputWrapperStyle={styles.composerInputWrapper}
|
||||
error={errorMessage}
|
||||
/>
|
||||
</KeyboardTranslateView>
|
||||
</FileDropZone>
|
||||
|
||||
{errorMessage ? <Text style={styles.errorText}>{errorMessage}</Text> : null}
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
@@ -482,11 +487,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
marginHorizontal: -theme.spacing[6],
|
||||
marginVertical: -theme.spacing[2],
|
||||
},
|
||||
errorText: {
|
||||
fontSize: theme.fontSize.base,
|
||||
color: theme.colors.destructive,
|
||||
lineHeight: 20,
|
||||
},
|
||||
composerSlot: {
|
||||
paddingBottom: theme.spacing[4],
|
||||
},
|
||||
|
||||
@@ -8,6 +8,21 @@ const request = {
|
||||
clientMessageId: "draft-1:initial-message",
|
||||
};
|
||||
|
||||
const workspaceRequest = {
|
||||
source: {
|
||||
kind: "worktree" as const,
|
||||
cwd: "/repo",
|
||||
projectId: "prj_1",
|
||||
worktreeSlug: "clever-fox",
|
||||
},
|
||||
firstAgentContext: { prompt: "Start the original task.", attachments: [] },
|
||||
agent: {
|
||||
config: { provider: "codex", cwd: "/repo", model: "gpt-6" },
|
||||
initialPrompt: "Start the original task.",
|
||||
clientMessageId: "draft-1:initial-message",
|
||||
},
|
||||
};
|
||||
|
||||
describe("draftCreationKey", () => {
|
||||
it("keeps the key for a retry of the same request, whatever its key order", () => {
|
||||
const reordered = {
|
||||
@@ -27,4 +42,52 @@ describe("draftCreationKey", () => {
|
||||
expect(key).not.toBe(draftCreationKey("draft-1", request));
|
||||
expect(key.startsWith("draft-1:")).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "isolation",
|
||||
edited: {
|
||||
...workspaceRequest,
|
||||
source: { kind: "directory" as const, path: "/repo", projectId: "prj_1" },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "project",
|
||||
edited: {
|
||||
...workspaceRequest,
|
||||
source: { ...workspaceRequest.source, projectId: "prj_2", cwd: "/other" },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "prompt",
|
||||
edited: {
|
||||
...workspaceRequest,
|
||||
firstAgentContext: { prompt: "hi", attachments: [] },
|
||||
agent: { ...workspaceRequest.agent, initialPrompt: "hi" },
|
||||
},
|
||||
},
|
||||
])(
|
||||
"gives a New workspace request with edited $name a new key on the same draft",
|
||||
({ edited }) => {
|
||||
const key = draftCreationKey("draft-1", edited);
|
||||
expect(key).not.toBe(draftCreationKey("draft-1", workspaceRequest));
|
||||
expect(key.startsWith("draft-1:")).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it("gives a New workspace request with a changed launch target a new key even when the wire request matches", () => {
|
||||
const emptyRequest = {
|
||||
source: { kind: "directory" as const, path: "/repo", projectId: "prj_1" },
|
||||
};
|
||||
const chatKey = draftCreationKey("draft-1", {
|
||||
request: emptyRequest,
|
||||
launchTarget: { kind: "chat" },
|
||||
});
|
||||
const terminalKey = draftCreationKey("draft-1", {
|
||||
request: emptyRequest,
|
||||
launchTarget: { kind: "terminal", profileId: "shell" },
|
||||
});
|
||||
expect(terminalKey).not.toBe(chatKey);
|
||||
expect(terminalKey.startsWith("draft-1:")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ComposerOptionControls } from "@/agent-controls/option-controls";
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import { Keyboard, StyleSheet as RNStyleSheet, Text, View } from "react-native";
|
||||
import { Keyboard, StyleSheet as RNStyleSheet, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
|
||||
@@ -536,16 +536,6 @@ export function WorkspaceDraftComposer({
|
||||
);
|
||||
return (
|
||||
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
|
||||
{formErrorMessage ? (
|
||||
<View
|
||||
style={styles.formErrorRow}
|
||||
dataSet={isComposerFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
|
||||
>
|
||||
<View style={styles.formError}>
|
||||
<Text style={styles.errorText}>{formErrorMessage}</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
{importPillPress && !isComposerFullscreen ? (
|
||||
<View style={styles.importPillRow} dataSet={CHAT_COLUMN_RAIL_DATASET}>
|
||||
<View style={styles.importPillContent}>
|
||||
@@ -577,6 +567,7 @@ export function WorkspaceDraftComposer({
|
||||
commandDraft={composerState.commandDraft}
|
||||
agentControls={composerAgentControls}
|
||||
isCompactLayout={isCompactComposerLayout}
|
||||
error={formErrorMessage || null}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
@@ -592,11 +583,6 @@ const animatedStaticStyles = RNStyleSheet.create({
|
||||
});
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
formErrorRow: {
|
||||
width: "100%",
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
alignItems: "center",
|
||||
},
|
||||
importPillRow: {
|
||||
width: "100%",
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
@@ -615,18 +601,4 @@ const styles = StyleSheet.create((theme) => ({
|
||||
maxWidth: theme.contentMaxWidth,
|
||||
flexDirection: "row",
|
||||
},
|
||||
formError: {
|
||||
width: "100%",
|
||||
maxWidth: theme.contentMaxWidth,
|
||||
marginBottom: theme.spacing[2],
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
paddingVertical: theme.spacing[2],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.destructive,
|
||||
},
|
||||
errorText: {
|
||||
color: theme.colors.destructive,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -8,6 +8,7 @@ import { createStore, type StoreApi } from "zustand/vanilla";
|
||||
import { useStore } from "zustand";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import {
|
||||
View,
|
||||
Pressable,
|
||||
@@ -1016,6 +1017,8 @@ interface ComposerProps {
|
||||
* `inputMode`.
|
||||
*/
|
||||
editingSession?: ComposerEditingSession;
|
||||
/** Caller-owned submission error rendered in the composer's shared error slot. */
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
const EMPTY_ARRAY: readonly QueuedMessage[] = [];
|
||||
@@ -1319,6 +1322,7 @@ function ComposerContentImpl({
|
||||
isCompactLayout: isCompactLayoutOverride,
|
||||
inputMode = "chat",
|
||||
editingSession: providedEditingSession,
|
||||
error: externalError,
|
||||
readOnly = false,
|
||||
submitLabel,
|
||||
placeholder,
|
||||
@@ -2544,14 +2548,13 @@ function ComposerContentImpl({
|
||||
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
|
||||
const messageInputAutoFocus = autoFocus && isDesktopWebBreakpoint && hasFinePointer;
|
||||
const submitLoadingPressHandler = isAgentRunning ? handleCancelAgent : undefined;
|
||||
const displayError = externalError || sendError;
|
||||
const sendErrorNode = useMemo(
|
||||
() =>
|
||||
sendError ? (
|
||||
<Text accessibilityRole="alert" style={styles.sendErrorText}>
|
||||
{sendError}
|
||||
</Text>
|
||||
displayError ? (
|
||||
<Alert variant="error" size="sm" description={displayError} testID="composer-error" />
|
||||
) : null,
|
||||
[sendError],
|
||||
[displayError],
|
||||
);
|
||||
const githubEmptyText = githubSearchResultsQuery.isFetching
|
||||
? t("composer.github.searching")
|
||||
@@ -2837,10 +2840,6 @@ const styles = StyleSheet.create((theme: Theme) => ({
|
||||
queueSendButton: {
|
||||
backgroundColor: theme.colors.accent,
|
||||
},
|
||||
sendErrorText: {
|
||||
color: theme.colors.palette.red[500],
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
})) as unknown as Record<string, object>;
|
||||
|
||||
const ThemedAttachmentSpinner = withUnistyles(LoadingSpinner);
|
||||
|
||||
@@ -110,6 +110,10 @@ function resolveAgentAutocompleteSnapshot(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function isSameSlashCommand(a: SlashCommandRange | null, b: SlashCommandRange | null): boolean {
|
||||
return a?.start === b?.start && a?.query === b?.query;
|
||||
}
|
||||
|
||||
interface DirectorySuggestionEntry {
|
||||
path: string;
|
||||
kind: "file" | "directory";
|
||||
@@ -746,9 +750,25 @@ export function useAgentAutocomplete(input: UseAgentAutocompleteInput): AgentAut
|
||||
);
|
||||
|
||||
const selectOptionFromKeyPress = useCallback(
|
||||
(option: AutocompleteOption, event?: AgentAutocompleteKeyPressEvent) =>
|
||||
onSelectOption(option, event?.input),
|
||||
[onSelectOption],
|
||||
(option: AutocompleteOption, event?: AgentAutocompleteKeyPressEvent) => {
|
||||
// The cursor reaches the menu after paint, so a key can land while the options still
|
||||
// belong to an older query. Never pick from that list. A click picks what the user sees.
|
||||
if (
|
||||
mode === "command" &&
|
||||
event &&
|
||||
!isSameSlashCommand(
|
||||
findActiveSlashCommand({
|
||||
text: event.input.text,
|
||||
cursorIndex: event.input.selection.start,
|
||||
}),
|
||||
activeSlashCommand,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
onSelectOption(option, event?.input);
|
||||
},
|
||||
[activeSlashCommand, mode, onSelectOption],
|
||||
);
|
||||
|
||||
const { selectedIndex, onKeyPress } = useAutocomplete({
|
||||
|
||||
@@ -21,6 +21,7 @@ import { useSessionStore, type Agent } from "@/stores/session-store";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { isAgentArchiving, setAgentArchiving } from "@/hooks/use-archive-agent";
|
||||
import { queryClient } from "@/data/query-client";
|
||||
import { checkoutStatusQueryKey } from "@/git/query-keys";
|
||||
import {
|
||||
HostRuntimeController,
|
||||
HostRuntimeStore,
|
||||
@@ -1748,7 +1749,7 @@ describe("HostRuntimeController", () => {
|
||||
});
|
||||
|
||||
latencies["relay:relay.paseo.sh:443"] = 30;
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await vi.advanceTimersByTimeAsync(240_000);
|
||||
await controller.runProbeCycleNow();
|
||||
expect(controller.getSnapshot().activeConnectionId).toBe("direct:lan:6767");
|
||||
|
||||
@@ -1807,6 +1808,429 @@ describe("HostRuntimeController", () => {
|
||||
await controller.stop();
|
||||
});
|
||||
|
||||
it("ignores busy active heartbeat spikes when comparing against an idle alternate probe", async () => {
|
||||
// Replays the recorded 10:04-10:08 relay sequence (#9149): the active relay has a ~250-300 ms
|
||||
// baseline over its recent heartbeats, spikes to 383/503/491 ms right before each alternate
|
||||
// probe, and the idle alternate measures 236/322/291 ms.
|
||||
useHostRuntimeClock();
|
||||
const host = makeHost({
|
||||
connections: [relayPrimary, relayAlternate],
|
||||
preferredConnectionId: relayPrimary.id,
|
||||
});
|
||||
const clients: FakeDaemonClient[] = [];
|
||||
let alternateProbes = 0;
|
||||
const latencies: Record<string, number | Error> = {
|
||||
[relayPrimary.id]: 260,
|
||||
[relayAlternate.id]: 280,
|
||||
};
|
||||
const baseDeps = makeDeps(latencies, clients);
|
||||
const controller = new HostRuntimeController({
|
||||
host,
|
||||
deps: {
|
||||
...baseDeps,
|
||||
connectToDaemon: async (input) => {
|
||||
if (input.connection.id === relayAlternate.id) {
|
||||
alternateProbes += 1;
|
||||
}
|
||||
return baseDeps.connectToDaemon(input);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await controller.start({ autoProbe: false });
|
||||
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
|
||||
const activeClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
|
||||
|
||||
const rounds = [
|
||||
{ intervalMs: 120_000, baseline: 295, spike: 383, alternate: 236 },
|
||||
{ intervalMs: 240_000, baseline: 251, spike: 503, alternate: 322 },
|
||||
{ intervalMs: 480_000, baseline: 341, spike: 491, alternate: 291 },
|
||||
];
|
||||
for (const round of rounds) {
|
||||
await vi.advanceTimersByTimeAsync(round.intervalMs - 10_000);
|
||||
activeClient.heartbeatReportsRtt(round.baseline);
|
||||
await controller.runProbeCycleNow();
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
activeClient.heartbeatReportsRtt(round.spike);
|
||||
latencies[relayAlternate.id] = round.alternate;
|
||||
await controller.runProbeCycleNow();
|
||||
}
|
||||
|
||||
expect(alternateProbes).toBe(4);
|
||||
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
|
||||
expect(controller.getSnapshot().client).toBe(activeClient);
|
||||
expect(activeClient.isDisposed()).toBe(false);
|
||||
await controller.stop();
|
||||
});
|
||||
|
||||
it("requires a proportional RTT improvement before switching away from a high-latency link", async () => {
|
||||
useHostRuntimeClock();
|
||||
const host = makeHost({
|
||||
connections: [relayPrimary, relayAlternate],
|
||||
preferredConnectionId: relayPrimary.id,
|
||||
});
|
||||
const clients: FakeDaemonClient[] = [];
|
||||
const latencies: Record<string, number | Error> = {
|
||||
[relayPrimary.id]: 300,
|
||||
[relayAlternate.id]: 320,
|
||||
};
|
||||
const controller = new HostRuntimeController({
|
||||
host,
|
||||
deps: makeDeps(latencies, clients),
|
||||
});
|
||||
|
||||
await controller.start({ autoProbe: false });
|
||||
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
|
||||
const activeClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
|
||||
|
||||
// 60 ms faster on a 300 ms link (20%) is noise, not enough to justify a switch.
|
||||
activeClient.heartbeatReportsRtt(300);
|
||||
latencies[relayAlternate.id] = 240;
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
await vi.advanceTimersByTimeAsync(30 * 60_000);
|
||||
await controller.runProbeCycleNow();
|
||||
}
|
||||
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
|
||||
|
||||
// 150 ms faster on a 300 ms link (50%) is a real win and switches after 3 consecutive probes.
|
||||
latencies[relayAlternate.id] = 150;
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
await vi.advanceTimersByTimeAsync(index === 0 ? 30 * 60_000 : 120_000);
|
||||
await controller.runProbeCycleNow();
|
||||
}
|
||||
expect(controller.getSnapshot().activeConnectionId).toBe(relayAlternate.id);
|
||||
await controller.stop();
|
||||
});
|
||||
|
||||
it("exponentially backs off inactive connection probes while the active connection keeps winning", async () => {
|
||||
useHostRuntimeClock();
|
||||
const host = makeHost({
|
||||
connections: [relayPrimary, relayAlternate],
|
||||
preferredConnectionId: relayPrimary.id,
|
||||
});
|
||||
const clients: FakeDaemonClient[] = [];
|
||||
let alternateProbes = 0;
|
||||
const baseDeps = makeDeps(
|
||||
{
|
||||
[relayPrimary.id]: 250,
|
||||
[relayAlternate.id]: 260,
|
||||
},
|
||||
clients,
|
||||
);
|
||||
const controller = new HostRuntimeController({
|
||||
host,
|
||||
deps: {
|
||||
...baseDeps,
|
||||
connectToDaemon: async (input) => {
|
||||
if (input.connection.id === relayAlternate.id) {
|
||||
alternateProbes += 1;
|
||||
}
|
||||
return baseDeps.connectToDaemon(input);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await controller.start({ autoProbe: false });
|
||||
const activeClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
|
||||
activeClient.heartbeatReportsRtt(250);
|
||||
expect(alternateProbes).toBe(1);
|
||||
|
||||
// First inactive online probe runs at 2m -> active wins, next interval backs off to 4m.
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await controller.runProbeCycleNow();
|
||||
expect(alternateProbes).toBe(2);
|
||||
|
||||
// At +2m (still < 4m), no inactive probe runs.
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await controller.runProbeCycleNow();
|
||||
expect(alternateProbes).toBe(2);
|
||||
|
||||
// At +4m total, second inactive probe runs -> backs off to 8m.
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await controller.runProbeCycleNow();
|
||||
expect(alternateProbes).toBe(3);
|
||||
|
||||
// At +6m (< 8m), still quiet; at +8m, third inactive probe runs -> backs off to 16m.
|
||||
await vi.advanceTimersByTimeAsync(6 * 60_000);
|
||||
await controller.runProbeCycleNow();
|
||||
expect(alternateProbes).toBe(3);
|
||||
await vi.advanceTimersByTimeAsync(2 * 60_000);
|
||||
await controller.runProbeCycleNow();
|
||||
expect(alternateProbes).toBe(4);
|
||||
|
||||
// Foreground verification resets backoff back to 2m without forcing an immediate probe.
|
||||
await vi.advanceTimersByTimeAsync(3 * 60_000);
|
||||
controller.ensureConnected({ verify: true });
|
||||
await controller.runProbeCycleNow();
|
||||
expect(alternateProbes).toBe(5);
|
||||
await controller.stop();
|
||||
});
|
||||
|
||||
it("keeps the active connection online while connecting the replacement during an adaptive switch", async () => {
|
||||
useHostRuntimeClock();
|
||||
const host = makeHost({
|
||||
connections: [relayPrimary, relayAlternate],
|
||||
preferredConnectionId: relayPrimary.id,
|
||||
});
|
||||
const clients: FakeDaemonClient[] = [];
|
||||
const latencies: Record<string, number | Error> = {
|
||||
[relayPrimary.id]: 300,
|
||||
[relayAlternate.id]: 320,
|
||||
};
|
||||
let replacementConnectGate: ReturnType<typeof createDeferred<void>> | null = null;
|
||||
let shouldFailReplacement = false;
|
||||
const baseDeps = makeDeps(latencies, clients);
|
||||
const controller = new HostRuntimeController({
|
||||
host,
|
||||
deps: {
|
||||
...baseDeps,
|
||||
createClient: (input) => {
|
||||
const client = baseDeps.createClient(input) as unknown as FakeDaemonClient;
|
||||
if (input.connection.id === relayAlternate.id) {
|
||||
const origConnect = client.connect.bind(client);
|
||||
client.connect = async () => {
|
||||
if (replacementConnectGate) {
|
||||
await replacementConnectGate.promise;
|
||||
}
|
||||
if (shouldFailReplacement) {
|
||||
throw new Error("replacement handshake failed");
|
||||
}
|
||||
return origConnect();
|
||||
};
|
||||
}
|
||||
return client as unknown as DaemonClient;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await controller.start({ autoProbe: false });
|
||||
const initialClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
|
||||
initialClient.heartbeatReportsRtt(300);
|
||||
latencies[relayAlternate.id] = 100;
|
||||
|
||||
const observedSnapshots: Array<{
|
||||
status: string;
|
||||
connectionId: string | null;
|
||||
hasClient: boolean;
|
||||
}> = [];
|
||||
const unsubscribe = controller.subscribe(() => {
|
||||
const snap = controller.getSnapshot();
|
||||
observedSnapshots.push({
|
||||
status: snap.connectionStatus,
|
||||
connectionId: snap.activeConnectionId,
|
||||
hasClient: snap.client !== null,
|
||||
});
|
||||
});
|
||||
|
||||
// Two wins first.
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await controller.runProbeCycleNow();
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await controller.runProbeCycleNow();
|
||||
|
||||
// Third win triggers a switch, but replacement connect fails: active client must stay online.
|
||||
shouldFailReplacement = true;
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await controller.runProbeCycleNow();
|
||||
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
|
||||
expect(controller.getSnapshot().connectionStatus).toBe("online");
|
||||
expect(controller.getSnapshot().client).toBe(initialClient);
|
||||
expect(initialClient.isDisposed()).toBe(false);
|
||||
|
||||
// Now let replacement succeed after a delay: host must stay online on initialClient while
|
||||
// replacement connects, and never emit connecting or client=null.
|
||||
shouldFailReplacement = false;
|
||||
observedSnapshots.length = 0;
|
||||
for (let index = 0; index < 2; index += 1) {
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await controller.runProbeCycleNow();
|
||||
}
|
||||
replacementConnectGate = createDeferred<void>();
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
const switchingCycle = controller.runProbeCycleNow();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
|
||||
expect(controller.getSnapshot().connectionStatus).toBe("online");
|
||||
expect(controller.getSnapshot().client).toBe(initialClient);
|
||||
expect(initialClient.isDisposed()).toBe(false);
|
||||
|
||||
replacementConnectGate.resolve();
|
||||
await switchingCycle;
|
||||
|
||||
expect(controller.getSnapshot().activeConnectionId).toBe(relayAlternate.id);
|
||||
expect(controller.getSnapshot().connectionStatus).toBe("online");
|
||||
expect(controller.getSnapshot().client).not.toBeNull();
|
||||
expect(controller.getSnapshot().client).not.toBe(initialClient);
|
||||
expect(initialClient.isDisposed()).toBe(true);
|
||||
expect(observedSnapshots.some((snap) => snap.status !== "online" || !snap.hasClient)).toBe(
|
||||
false,
|
||||
);
|
||||
|
||||
unsubscribe();
|
||||
await controller.stop();
|
||||
});
|
||||
|
||||
it("keeps active client status updates working after a failed make-before-break upgrade", async () => {
|
||||
useHostRuntimeClock();
|
||||
const host = makeHost({
|
||||
connections: [relayPrimary, relayAlternate],
|
||||
preferredConnectionId: relayPrimary.id,
|
||||
});
|
||||
const clients: FakeDaemonClient[] = [];
|
||||
const latencies: Record<string, number | Error> = {
|
||||
[relayPrimary.id]: 300,
|
||||
[relayAlternate.id]: 320,
|
||||
};
|
||||
const baseDeps = makeDeps(latencies, clients);
|
||||
const controller = new HostRuntimeController({
|
||||
host,
|
||||
deps: {
|
||||
...baseDeps,
|
||||
createClient: (input) => {
|
||||
const client = baseDeps.createClient(input) as unknown as FakeDaemonClient;
|
||||
if (input.connection.id === relayAlternate.id) {
|
||||
client.connect = async () => {
|
||||
throw new Error("replacement handshake failed");
|
||||
};
|
||||
}
|
||||
return client as unknown as DaemonClient;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await controller.start({ autoProbe: false });
|
||||
const initialClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
|
||||
initialClient.heartbeatReportsRtt(300);
|
||||
latencies[relayAlternate.id] = 100;
|
||||
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await controller.runProbeCycleNow();
|
||||
}
|
||||
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
|
||||
expect(controller.getSnapshot().connectionStatus).toBe("online");
|
||||
|
||||
initialClient.setConnectionState({ status: "disconnected", reason: "transport closed" });
|
||||
expect(controller.getSnapshot().connectionStatus).toBe("error");
|
||||
expect(controller.getSnapshot().lastError).toBe("transport closed");
|
||||
await controller.stop();
|
||||
});
|
||||
|
||||
it("aborts a pending make-before-break upgrade when the candidate connection is removed", async () => {
|
||||
useHostRuntimeClock();
|
||||
const host = makeHost({
|
||||
connections: [relayPrimary, relayAlternate],
|
||||
preferredConnectionId: relayPrimary.id,
|
||||
});
|
||||
const clients: FakeDaemonClient[] = [];
|
||||
const latencies: Record<string, number | Error> = {
|
||||
[relayPrimary.id]: 300,
|
||||
[relayAlternate.id]: 320,
|
||||
};
|
||||
const replacementGate = createDeferred<void>();
|
||||
const replacementClients: FakeDaemonClient[] = [];
|
||||
const baseDeps = makeDeps(latencies, clients);
|
||||
const controller = new HostRuntimeController({
|
||||
host,
|
||||
deps: {
|
||||
...baseDeps,
|
||||
createClient: (input) => {
|
||||
const client = baseDeps.createClient(input) as unknown as FakeDaemonClient;
|
||||
if (input.connection.id === relayAlternate.id) {
|
||||
replacementClients.push(client);
|
||||
const origConnect = client.connect.bind(client);
|
||||
client.connect = async () => {
|
||||
await replacementGate.promise;
|
||||
return origConnect();
|
||||
};
|
||||
}
|
||||
return client as unknown as DaemonClient;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await controller.start({ autoProbe: false });
|
||||
const initialClient = controller.getSnapshot().client as unknown as FakeDaemonClient;
|
||||
initialClient.heartbeatReportsRtt(300);
|
||||
latencies[relayAlternate.id] = 100;
|
||||
|
||||
for (let index = 0; index < 2; index += 1) {
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await controller.runProbeCycleNow();
|
||||
}
|
||||
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
const switchingCycle = controller.runProbeCycleNow();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(replacementClients).toHaveLength(1);
|
||||
|
||||
const updatePromise = controller.updateHost({
|
||||
...host,
|
||||
connections: [relayPrimary],
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
replacementGate.resolve();
|
||||
await Promise.all([switchingCycle, updatePromise]);
|
||||
|
||||
expect(controller.getSnapshot().activeConnectionId).toBe(relayPrimary.id);
|
||||
expect(controller.getSnapshot().connectionStatus).toBe("online");
|
||||
expect(controller.getSnapshot().client).toBe(initialClient);
|
||||
expect(initialClient.isDisposed()).toBe(false);
|
||||
expect(replacementClients[0]?.isDisposed()).toBe(true);
|
||||
await controller.stop();
|
||||
});
|
||||
|
||||
it("runs store cache recovery when a make-before-break adaptive switch advances the online epoch", async () => {
|
||||
useHostRuntimeClock();
|
||||
const host = makeHost({
|
||||
serverId: "srv_upgrade_cache_recovery",
|
||||
connections: [relayPrimary, relayAlternate],
|
||||
preferredConnectionId: relayPrimary.id,
|
||||
});
|
||||
const clients: FakeDaemonClient[] = [];
|
||||
const latencies: Record<string, number | Error> = {
|
||||
[relayPrimary.id]: 300,
|
||||
[relayAlternate.id]: 320,
|
||||
};
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: makeDeps(latencies, clients),
|
||||
});
|
||||
const queryKey = checkoutStatusQueryKey(host.serverId, "/repo");
|
||||
|
||||
try {
|
||||
store.syncHosts([host]);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(store.getSnapshot(host.serverId)?.connectionStatus).toBe("online");
|
||||
const initialEpoch = store.getSnapshot(host.serverId)?.connectionEpoch ?? 0;
|
||||
const activeClient = store.getSnapshot(host.serverId)?.client as unknown as FakeDaemonClient;
|
||||
const initialHistoryGen =
|
||||
useSessionStore.getState().sessions[host.serverId]?.historySyncGeneration ?? 0;
|
||||
|
||||
queryClient.setQueryData(queryKey, { branch: "main" });
|
||||
expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(false);
|
||||
|
||||
activeClient.heartbeatReportsRtt(300);
|
||||
latencies[relayAlternate.id] = 100;
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await store.runProbeCycleNow(host.serverId);
|
||||
}
|
||||
|
||||
expect(store.getSnapshot(host.serverId)?.activeConnectionId).toBe(relayAlternate.id);
|
||||
expect(store.getSnapshot(host.serverId)?.connectionStatus).toBe("online");
|
||||
expect(store.getSnapshot(host.serverId)?.connectionEpoch).toBeGreaterThan(initialEpoch);
|
||||
expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(true);
|
||||
expect(
|
||||
useSessionStore.getState().sessions[host.serverId]?.historySyncGeneration ?? 0,
|
||||
).toBeGreaterThan(initialHistoryGen);
|
||||
} finally {
|
||||
queryClient.removeQueries({ queryKey });
|
||||
store.syncHosts([]);
|
||||
}
|
||||
});
|
||||
|
||||
it("exposes one snapshot with active connection and status from same source", async () => {
|
||||
const host = makeHost();
|
||||
const clients: FakeDaemonClient[] = [];
|
||||
|
||||
@@ -245,8 +245,11 @@ export interface HostRuntimeStartOptions {
|
||||
const PROBE_TICK_MS = 2_000;
|
||||
const PROBE_STEADY_MS = 10_000;
|
||||
const PROBE_MAX_BACKOFF_MS = 30_000;
|
||||
const PROBE_INACTIVE_WHILE_ONLINE_MS = 120_000;
|
||||
const PROBE_INACTIVE_WHILE_ONLINE_INITIAL_MS = 120_000;
|
||||
const PROBE_INACTIVE_WHILE_ONLINE_MAX_MS = 30 * 60_000;
|
||||
const ACTIVE_RTT_WINDOW_MS = 60_000;
|
||||
const ADAPTIVE_SWITCH_THRESHOLD_MS = 40;
|
||||
const ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO = 0.35;
|
||||
const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3;
|
||||
const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000;
|
||||
|
||||
@@ -549,13 +552,14 @@ function probeIntervalForConnection(
|
||||
firstSeenAt: number,
|
||||
isActiveOnline: boolean,
|
||||
hasActiveOnlineConnection: boolean,
|
||||
inactiveOnlineIntervalMs: number,
|
||||
now: number,
|
||||
): number {
|
||||
if (isActiveOnline) {
|
||||
return PROBE_STEADY_MS;
|
||||
}
|
||||
if (hasActiveOnlineConnection) {
|
||||
return PROBE_INACTIVE_WHILE_ONLINE_MS;
|
||||
return inactiveOnlineIntervalMs;
|
||||
}
|
||||
const age = now - firstSeenAt;
|
||||
if (age < 10_000) return 2_000;
|
||||
@@ -728,6 +732,8 @@ export class HostRuntimeController {
|
||||
private connectionLastProbedAt = new Map<string, number>();
|
||||
private switchCandidateConnectionId: string | null = null;
|
||||
private switchCandidateHitCount = 0;
|
||||
private inactiveOnlineProbeBackoffStep = 0;
|
||||
private activeRttSamples: Array<{ at: number; rttMs: number }> = [];
|
||||
private clientIdPromise: Promise<string> | null = null;
|
||||
private clientIdHash: string | null = null;
|
||||
private switchRequestVersion = 0;
|
||||
@@ -823,6 +829,9 @@ export class HostRuntimeController {
|
||||
this.activeClient = null;
|
||||
await prev.close().catch(() => undefined);
|
||||
}
|
||||
this.resetSwitchCandidate();
|
||||
this.clearActiveRttSamples();
|
||||
this.resetInactiveOnlineProbeBackoff();
|
||||
this.applyConnectionEvent({ type: "stopped" });
|
||||
this.updateSnapshot({
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
@@ -832,11 +841,15 @@ export class HostRuntimeController {
|
||||
|
||||
async updateHost(host: HostProfile): Promise<void> {
|
||||
const passwordChanged = this.host.password !== host.password;
|
||||
const connectionsChanged = !equal(this.host.connections, host.connections);
|
||||
if (passwordChanged) {
|
||||
this.probeRequestVersion += 1;
|
||||
this.authRejectedConnectionIds.clear();
|
||||
this.updateSnapshot({ authFailureReason: null });
|
||||
}
|
||||
if (passwordChanged || connectionsChanged) {
|
||||
this.resetInactiveOnlineProbeBackoff();
|
||||
}
|
||||
const activeConnectionId = this.snapshot.activeConnectionId;
|
||||
const previousActiveConnection = findConnectionById(this.host, activeConnectionId);
|
||||
this.host = host;
|
||||
@@ -862,6 +875,9 @@ export class HostRuntimeController {
|
||||
}
|
||||
|
||||
ensureConnected(options?: { verify?: boolean }): void {
|
||||
if (options?.verify) {
|
||||
this.resetInactiveOnlineProbeBackoff();
|
||||
}
|
||||
this.activeClient?.ensureConnected(options);
|
||||
}
|
||||
|
||||
@@ -962,6 +978,7 @@ export class HostRuntimeController {
|
||||
const activeConnectionId = this.snapshot.activeConnectionId;
|
||||
const hasActiveOnlineConnection = isOnline && activeConnectionId !== null;
|
||||
|
||||
const inactiveOnlineIntervalMs = this.inactiveOnlineProbeIntervalMs();
|
||||
const connectionsToProbe = this.host.connections.filter((connection) => {
|
||||
if (this.authRejectedConnectionIds.has(connection.id)) return false;
|
||||
const lastProbed = this.connectionLastProbedAt.get(connection.id);
|
||||
@@ -974,6 +991,7 @@ export class HostRuntimeController {
|
||||
firstSeen,
|
||||
isActiveOnline,
|
||||
hasActiveOnlineConnection,
|
||||
inactiveOnlineIntervalMs,
|
||||
now,
|
||||
);
|
||||
return now - lastProbed >= interval;
|
||||
@@ -1081,10 +1099,10 @@ export class HostRuntimeController {
|
||||
|
||||
// Adaptive switching counts fresh comparisons only. The probe map keeps the last known
|
||||
// sample per connection for display and failover; a streak hit needs a candidate measured
|
||||
// in this cycle and a heartbeat RTT from the socket that is active right now. Re-reading
|
||||
// the cached map at every ten-second active tick turned one idle-probe sample into three
|
||||
// "consecutive" wins, and a reconnected socket inherited its predecessor's RTT, so a
|
||||
// working relay connection was replaced within seconds of coming online.
|
||||
// in this cycle and a baseline RTT from the socket that is active right now. Using the
|
||||
// rolling minimum of recent active heartbeats filters out single busy/stalled ticks so a
|
||||
// loaded working socket does not lose to an idle probe, and a proportional threshold avoids
|
||||
// flapping on normal jitter on high-RTT links.
|
||||
const sampledCandidates = connectionsToProbe.filter(
|
||||
(connection) => connection.id !== currentActiveConnectionId,
|
||||
);
|
||||
@@ -1102,22 +1120,29 @@ export class HostRuntimeController {
|
||||
})
|
||||
.sort((left, right) => left.latencyMs - right.latencyMs)[0] ?? null;
|
||||
if (!fastest) {
|
||||
// Every candidate sampled this cycle failed: that breaks the streak.
|
||||
// Every candidate sampled this cycle failed: that breaks the streak and backs off.
|
||||
this.resetSwitchCandidate();
|
||||
this.advanceInactiveOnlineProbeBackoff();
|
||||
return;
|
||||
}
|
||||
|
||||
const activeRttMs = this.currentActiveSocketRttMs();
|
||||
const activeRttMs = this.currentActiveSocketBaselineRttMs(performance.now());
|
||||
if (activeRttMs === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requiredImprovementMs = Math.max(
|
||||
ADAPTIVE_SWITCH_THRESHOLD_MS,
|
||||
activeRttMs * ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO,
|
||||
);
|
||||
const improvement = activeRttMs - fastest.latencyMs;
|
||||
if (improvement < ADAPTIVE_SWITCH_THRESHOLD_MS) {
|
||||
if (improvement < requiredImprovementMs) {
|
||||
this.resetSwitchCandidate();
|
||||
this.advanceInactiveOnlineProbeBackoff();
|
||||
return;
|
||||
}
|
||||
|
||||
this.resetInactiveOnlineProbeBackoff();
|
||||
if (this.switchCandidateConnectionId === fastest.connectionId) {
|
||||
this.switchCandidateHitCount += 1;
|
||||
} else {
|
||||
@@ -1130,6 +1155,7 @@ export class HostRuntimeController {
|
||||
await this.switchToConnection({
|
||||
connectionId: fastest.connectionId,
|
||||
expectedProbeVersion: requestVersion,
|
||||
keepActiveUntilConnected: true,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1194,6 +1220,7 @@ export class HostRuntimeController {
|
||||
return;
|
||||
}
|
||||
if (rttMs !== null) {
|
||||
this.recordActiveRttSample(rttMs, performance.now());
|
||||
probeByConnectionId.set(connection.id, {
|
||||
status: "available",
|
||||
latencyMs: rttMs,
|
||||
@@ -1245,6 +1272,45 @@ export class HostRuntimeController {
|
||||
return client.getLastLivenessRttMs();
|
||||
}
|
||||
|
||||
private recordActiveRttSample(rttMs: number, now: number): void {
|
||||
this.activeRttSamples = this.activeRttSamples.filter(
|
||||
(sample) => now - sample.at <= ACTIVE_RTT_WINDOW_MS,
|
||||
);
|
||||
this.activeRttSamples.push({ at: now, rttMs });
|
||||
}
|
||||
|
||||
private clearActiveRttSamples(): void {
|
||||
this.activeRttSamples = [];
|
||||
}
|
||||
|
||||
private currentActiveSocketBaselineRttMs(now: number): number | null {
|
||||
const currentRttMs = this.currentActiveSocketRttMs();
|
||||
if (currentRttMs === null) return null;
|
||||
this.recordActiveRttSample(currentRttMs, now);
|
||||
let baseline = this.activeRttSamples[0]!.rttMs;
|
||||
for (const sample of this.activeRttSamples) {
|
||||
if (sample.rttMs < baseline) baseline = sample.rttMs;
|
||||
}
|
||||
return baseline;
|
||||
}
|
||||
|
||||
private inactiveOnlineProbeIntervalMs(): number {
|
||||
return Math.min(
|
||||
PROBE_INACTIVE_WHILE_ONLINE_INITIAL_MS * 2 ** this.inactiveOnlineProbeBackoffStep,
|
||||
PROBE_INACTIVE_WHILE_ONLINE_MAX_MS,
|
||||
);
|
||||
}
|
||||
|
||||
private advanceInactiveOnlineProbeBackoff(): void {
|
||||
if (this.inactiveOnlineProbeIntervalMs() < PROBE_INACTIVE_WHILE_ONLINE_MAX_MS) {
|
||||
this.inactiveOnlineProbeBackoffStep += 1;
|
||||
}
|
||||
}
|
||||
|
||||
private resetInactiveOnlineProbeBackoff(): void {
|
||||
this.inactiveOnlineProbeBackoffStep = 0;
|
||||
}
|
||||
|
||||
private resetSwitchCandidate(): void {
|
||||
this.switchCandidateConnectionId = null;
|
||||
this.switchCandidateHitCount = 0;
|
||||
@@ -1434,6 +1500,7 @@ export class HostRuntimeController {
|
||||
connectionId: string;
|
||||
expectedProbeVersion?: number;
|
||||
existingClient?: DaemonClient;
|
||||
keepActiveUntilConnected?: boolean;
|
||||
}): Promise<void> {
|
||||
const { connectionId, expectedProbeVersion, existingClient } = input;
|
||||
if (!this.canProceedForProbe(expectedProbeVersion)) {
|
||||
@@ -1455,6 +1522,24 @@ export class HostRuntimeController {
|
||||
return;
|
||||
}
|
||||
|
||||
const makeBeforeBreak =
|
||||
Boolean(input.keepActiveUntilConnected) &&
|
||||
!existingClient &&
|
||||
this.activeClient !== null &&
|
||||
this.connectionMachineState.tag === "online";
|
||||
|
||||
const nextGeneration = this.snapshot.clientGeneration + 1;
|
||||
if (makeBeforeBreak) {
|
||||
await this.switchToConnectionMakeBeforeBreak({
|
||||
connection,
|
||||
clientId,
|
||||
nextGeneration,
|
||||
requestVersion,
|
||||
expectedProbeVersion,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await this.disposePreviousActiveClient();
|
||||
|
||||
if (!this.isSwitchStillValid(requestVersion, expectedProbeVersion)) {
|
||||
@@ -1462,7 +1547,6 @@ export class HostRuntimeController {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextGeneration = this.snapshot.clientGeneration + 1;
|
||||
const client =
|
||||
existingClient ??
|
||||
this.deps.createClient({
|
||||
@@ -1479,6 +1563,8 @@ export class HostRuntimeController {
|
||||
}
|
||||
|
||||
this.activeClient = client;
|
||||
this.clearActiveRttSamples();
|
||||
this.resetInactiveOnlineProbeBackoff();
|
||||
this.applyConnectionEvent({
|
||||
type: "select_connection",
|
||||
connectionId: connection.id,
|
||||
@@ -1490,67 +1576,148 @@ export class HostRuntimeController {
|
||||
client: null,
|
||||
});
|
||||
|
||||
const failConnection = async (error: unknown) => {
|
||||
if (!this.isCurrentSwitchRequest(requestVersion) || this.activeClient !== client) return;
|
||||
const authFailure = getConnectionAuthFailureReason(error);
|
||||
if (authFailure) this.authRejectedConnectionIds.add(connection.id);
|
||||
this.unsubscribeClientStatus?.();
|
||||
this.unsubscribeClientStatus = null;
|
||||
this.unsubscribeClientHandlers?.();
|
||||
this.unsubscribeClientHandlers = null;
|
||||
client.setReconnectEnabled(false);
|
||||
this.applyConnectionEvent({ type: "connect_failed", message: toErrorMessage(error) });
|
||||
this.updateSnapshot({
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
client: null,
|
||||
authFailureReason: authFailure,
|
||||
});
|
||||
if (authFailure) {
|
||||
const probes = new Map(this.snapshot.probeByConnectionId);
|
||||
probes.set(connection.id, { status: "unavailable", latencyMs: null });
|
||||
this.updateSnapshot({ probeByConnectionId: probes });
|
||||
for (const candidate of this.host.connections) {
|
||||
if (!this.authRejectedConnectionIds.has(candidate.id)) {
|
||||
this.connectionLastProbedAt.delete(candidate.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
await client.close();
|
||||
} catch {
|
||||
/* Preserve the compatibility/connection error. */
|
||||
}
|
||||
if (
|
||||
authFailure &&
|
||||
this.host.connections.some((candidate) => !this.authRejectedConnectionIds.has(candidate.id))
|
||||
) {
|
||||
void this.runProbeCycleNow();
|
||||
}
|
||||
};
|
||||
try {
|
||||
if (!existingClient) await client.connect();
|
||||
if (!this.isCurrentSwitchRequest(requestVersion) || this.activeClient !== client) return;
|
||||
this.unsubscribeClientHandlers =
|
||||
this.deps.mountClientHandlers?.({ client, host: this.host, connection }) ?? null;
|
||||
this.unsubscribeClientStatus = client.subscribeConnectionStatus((state) => {
|
||||
if (!this.isCurrentSwitchRequest(requestVersion) || this.activeClient !== client) return;
|
||||
if (client.authFailureReason) {
|
||||
void failConnection(new DaemonAuthenticationError(client.authFailureReason));
|
||||
return;
|
||||
}
|
||||
if (state.status === "connected") this.learnRelaySecurity(client, connection.id);
|
||||
// Switch evidence belongs to the socket it was measured against.
|
||||
if (state.status !== "connected") this.resetSwitchCandidate();
|
||||
this.applyConnectionEvent({ type: "client_state", state, lastError: client.lastError });
|
||||
this.updateSnapshot({
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
...this.buildAgentDirectoryStatusPatch(),
|
||||
client,
|
||||
authFailureReason: null,
|
||||
});
|
||||
});
|
||||
this.attachActiveClient({ client, connection });
|
||||
} catch (error) {
|
||||
await failConnection(error);
|
||||
await this.failActiveConnection({ client, connection, error });
|
||||
}
|
||||
}
|
||||
|
||||
private async switchToConnectionMakeBeforeBreak(input: {
|
||||
connection: HostConnection;
|
||||
clientId: string;
|
||||
nextGeneration: number;
|
||||
requestVersion: number;
|
||||
expectedProbeVersion?: number;
|
||||
}): Promise<void> {
|
||||
const { connection, clientId, nextGeneration, requestVersion, expectedProbeVersion } = input;
|
||||
const replacement = this.deps.createClient({
|
||||
host: this.host,
|
||||
connection,
|
||||
clientId,
|
||||
runtimeGeneration: nextGeneration,
|
||||
});
|
||||
replacement.setReconnectEnabled(false);
|
||||
try {
|
||||
await replacement.connect();
|
||||
} catch (error) {
|
||||
const authFailure = getConnectionAuthFailureReason(error);
|
||||
if (authFailure) {
|
||||
this.authRejectedConnectionIds.add(connection.id);
|
||||
const probes = new Map(this.snapshot.probeByConnectionId);
|
||||
probes.set(connection.id, { status: "unavailable", latencyMs: null });
|
||||
this.updateSnapshot({ probeByConnectionId: probes });
|
||||
}
|
||||
await replacement.close().catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const resolveValidTarget = (): HostConnection | null => {
|
||||
if (!this.isSwitchStillValid(requestVersion, expectedProbeVersion)) return null;
|
||||
const saved = findConnectionById(this.host, connection.id);
|
||||
if (!saved || connectionNeedsNewClient(connection, saved, replacement)) return null;
|
||||
return saved;
|
||||
};
|
||||
|
||||
if (!resolveValidTarget()) {
|
||||
await replacement.close().catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
replacement.setReconnectEnabled(true);
|
||||
await this.disposePreviousActiveClient();
|
||||
|
||||
const target = resolveValidTarget();
|
||||
if (!target) {
|
||||
await replacement.close().catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
this.activeClient = replacement;
|
||||
this.clearActiveRttSamples();
|
||||
this.resetInactiveOnlineProbeBackoff();
|
||||
this.applyConnectionEvent({
|
||||
type: "select_connection",
|
||||
connectionId: target.id,
|
||||
connection: toActiveConnection(target),
|
||||
});
|
||||
this.snapshot = { ...this.snapshot, clientGeneration: nextGeneration };
|
||||
this.attachActiveClient({ client: replacement, connection: target });
|
||||
}
|
||||
|
||||
private attachActiveClient(input: { client: DaemonClient; connection: HostConnection }): void {
|
||||
const { client, connection } = input;
|
||||
this.unsubscribeClientHandlers =
|
||||
this.deps.mountClientHandlers?.({ client, host: this.host, connection }) ?? null;
|
||||
this.unsubscribeClientStatus = client.subscribeConnectionStatus((state) => {
|
||||
if (this.activeClient !== client) return;
|
||||
if (client.authFailureReason) {
|
||||
void this.failActiveConnection({
|
||||
client,
|
||||
connection,
|
||||
error: new DaemonAuthenticationError(client.authFailureReason),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (state.status === "connected") this.learnRelaySecurity(client, connection.id);
|
||||
// Switch evidence belongs to the socket it was measured against.
|
||||
if (state.status !== "connected") {
|
||||
this.resetSwitchCandidate();
|
||||
this.clearActiveRttSamples();
|
||||
this.resetInactiveOnlineProbeBackoff();
|
||||
}
|
||||
this.applyConnectionEvent({ type: "client_state", state, lastError: client.lastError });
|
||||
this.updateSnapshot({
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
...this.buildAgentDirectoryStatusPatch(),
|
||||
client,
|
||||
authFailureReason: null,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private async failActiveConnection(input: {
|
||||
client: DaemonClient;
|
||||
connection: HostConnection;
|
||||
error: unknown;
|
||||
}): Promise<void> {
|
||||
const { client, connection, error } = input;
|
||||
if (this.activeClient !== client) return;
|
||||
const authFailure = getConnectionAuthFailureReason(error);
|
||||
if (authFailure) this.authRejectedConnectionIds.add(connection.id);
|
||||
this.unsubscribeClientStatus?.();
|
||||
this.unsubscribeClientStatus = null;
|
||||
this.unsubscribeClientHandlers?.();
|
||||
this.unsubscribeClientHandlers = null;
|
||||
client.setReconnectEnabled(false);
|
||||
this.applyConnectionEvent({ type: "connect_failed", message: toErrorMessage(error) });
|
||||
this.updateSnapshot({
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
client: null,
|
||||
authFailureReason: authFailure,
|
||||
});
|
||||
if (authFailure) {
|
||||
const probes = new Map(this.snapshot.probeByConnectionId);
|
||||
probes.set(connection.id, { status: "unavailable", latencyMs: null });
|
||||
this.updateSnapshot({ probeByConnectionId: probes });
|
||||
for (const candidate of this.host.connections) {
|
||||
if (!this.authRejectedConnectionIds.has(candidate.id)) {
|
||||
this.connectionLastProbedAt.delete(candidate.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
await client.close();
|
||||
} catch {
|
||||
/* Preserve the compatibility/connection error. */
|
||||
}
|
||||
if (
|
||||
authFailure &&
|
||||
this.host.connections.some((candidate) => !this.authRejectedConnectionIds.has(candidate.id))
|
||||
) {
|
||||
void this.runProbeCycleNow();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1693,6 +1860,7 @@ export class HostRuntimeStore {
|
||||
private hostRegistryStatus: HostRegistryStatus = "loading";
|
||||
private deps: HostRuntimeControllerDeps;
|
||||
private lastConnectionStatusByServer = new Map<string, HostRuntimeConnectionStatus>();
|
||||
private lastOnlineEpochByServer = new Map<string, number>();
|
||||
private connectionStatusStartedAtByServer = new Map<string, number>();
|
||||
private queuedAgentDrainInFlight = new Set<string>();
|
||||
private directorySyncByServer = new Map<string, DirectorySync>();
|
||||
@@ -1950,6 +2118,7 @@ export class HostRuntimeStore {
|
||||
|
||||
rekeyMap(this.controllers, oldServerId, newServerId);
|
||||
rekeyMap(this.lastConnectionStatusByServer, oldServerId, newServerId);
|
||||
rekeyMap(this.lastOnlineEpochByServer, oldServerId, newServerId);
|
||||
rekeyMap(this.connectionStatusStartedAtByServer, oldServerId, newServerId);
|
||||
this.replicaCache.reconcileServerId(oldServerId, newServerId);
|
||||
projectIconCache.reconcileServerId(oldServerId, newServerId);
|
||||
@@ -2442,6 +2611,7 @@ export class HostRuntimeStore {
|
||||
this.fleetDirectoryDemand.delete(serverId);
|
||||
this.controllers.delete(serverId);
|
||||
this.lastConnectionStatusByServer.delete(serverId);
|
||||
this.lastOnlineEpochByServer.delete(serverId);
|
||||
this.connectionStatusStartedAtByServer.delete(serverId);
|
||||
this.directorySyncByServer.get(serverId)?.dispose();
|
||||
this.directorySyncByServer.delete(serverId);
|
||||
@@ -2492,6 +2662,9 @@ export class HostRuntimeStore {
|
||||
);
|
||||
const initialSnapshot = controller.getSnapshot();
|
||||
this.lastConnectionStatusByServer.set(host.serverId, initialSnapshot.connectionStatus);
|
||||
if (initialSnapshot.connectionStatus === "online") {
|
||||
this.lastOnlineEpochByServer.set(host.serverId, initialSnapshot.connectionEpoch);
|
||||
}
|
||||
this.connectionStatusStartedAtByServer.set(host.serverId, Date.now());
|
||||
controller.subscribe(() => {
|
||||
const snapshot = controller.getSnapshot();
|
||||
@@ -2591,6 +2764,7 @@ export class HostRuntimeStore {
|
||||
const controller = this.controllers.get(serverId);
|
||||
if (!controller) {
|
||||
this.lastConnectionStatusByServer.delete(serverId);
|
||||
this.lastOnlineEpochByServer.delete(serverId);
|
||||
this.connectionStatusStartedAtByServer.delete(serverId);
|
||||
return;
|
||||
}
|
||||
@@ -2605,6 +2779,7 @@ export class HostRuntimeStore {
|
||||
},
|
||||
});
|
||||
const previousStatus = this.lastConnectionStatusByServer.get(serverId);
|
||||
const previousOnlineEpoch = this.lastOnlineEpochByServer.get(serverId);
|
||||
const statusChanged = previousStatus !== snapshot.connectionStatus;
|
||||
const isUnavailable =
|
||||
snapshot.connectionStatus !== "online" && snapshot.connectionStatus !== "idle";
|
||||
@@ -2615,7 +2790,11 @@ export class HostRuntimeStore {
|
||||
}
|
||||
this.lastConnectionStatusByServer.set(serverId, snapshot.connectionStatus);
|
||||
const didTransitionOnline =
|
||||
snapshot.connectionStatus === "online" && previousStatus !== "online";
|
||||
snapshot.connectionStatus === "online" &&
|
||||
(previousStatus !== "online" || previousOnlineEpoch !== snapshot.connectionEpoch);
|
||||
if (snapshot.connectionStatus === "online") {
|
||||
this.lastOnlineEpochByServer.set(serverId, snapshot.connectionEpoch);
|
||||
}
|
||||
if (didTransitionOnline) {
|
||||
useSessionStore.getState().bumpHistorySyncGeneration(serverId);
|
||||
for (const child of this.controllers.values()) void child.reconnectVia(serverId);
|
||||
|
||||
@@ -24,6 +24,7 @@ import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
|
||||
import { MenuHeader } from "@/components/headers/menu-header";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { draftCreationKey } from "@/composer/draft/creation-key";
|
||||
import { useAgentInputDraft } from "@/composer/draft/input-draft";
|
||||
import { useForgeSearchQuery } from "@/git/use-forge-search-query";
|
||||
import { getForgePresentation } from "@/git/forge";
|
||||
@@ -336,6 +337,7 @@ interface WorkspaceCreationResult {
|
||||
|
||||
async function createMultiplicityWorkspace(input: {
|
||||
idempotencyKey: string;
|
||||
launchTarget: LaunchTarget;
|
||||
worktreeSlug: string;
|
||||
client: NonNullable<ReturnType<typeof useHostRuntimeClient>>;
|
||||
isolation: "local" | "worktree";
|
||||
@@ -365,10 +367,8 @@ async function createMultiplicityWorkspace(input: {
|
||||
prompt: input.prompt,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
const payload = await input.client.createWorkspace({
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
const request: Omit<CreateWorkspaceRequestOptions, "idempotencyKey" | "onEvent"> = {
|
||||
agent: input.agent,
|
||||
onEvent: input.onEvent,
|
||||
source: isWorktree
|
||||
? {
|
||||
kind: "worktree",
|
||||
@@ -387,6 +387,14 @@ async function createMultiplicityWorkspace(input: {
|
||||
},
|
||||
...(firstAgentContext ? { firstAgentContext } : {}),
|
||||
...(Object.keys(input.metadata).length > 0 ? { metadata: { ...input.metadata } } : {}),
|
||||
};
|
||||
const payload = await input.client.createWorkspace({
|
||||
...request,
|
||||
idempotencyKey: draftCreationKey(input.idempotencyKey, {
|
||||
request,
|
||||
launchTarget: input.launchTarget,
|
||||
}),
|
||||
onEvent: input.onEvent,
|
||||
});
|
||||
if (payload.error || !payload.workspace) {
|
||||
throw new Error(payload.error ?? input.createFailedMessage);
|
||||
@@ -508,7 +516,7 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
|
||||
});
|
||||
const images = await encodeImages(wirePayload.images);
|
||||
let navigated = false;
|
||||
let outcome: SubmitOutcome = "background";
|
||||
const delivery: { outcome: SubmitOutcome } = { outcome: "background" };
|
||||
const initialAgent: NonNullable<CreateWorkspaceRequestOptions["agent"]> = {
|
||||
config: {
|
||||
provider,
|
||||
@@ -545,7 +553,7 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
|
||||
provider,
|
||||
composerState,
|
||||
});
|
||||
outcome = submitWorkspaceDraft({
|
||||
delivery.outcome = submitWorkspaceDraft({
|
||||
clearConsumedDraft,
|
||||
draftKey: input.draftKey,
|
||||
draftContextScopeKey: input.draftContextScopeKey,
|
||||
@@ -571,9 +579,15 @@ async function createWorkspaceChatAgent(input: CreateChatAgentInput): Promise<Su
|
||||
};
|
||||
// A retry after a failed agent start belongs to the ready workspace's draft, not to this creation.
|
||||
const agentCreation = { result: Promise.resolve().then(() => execute()) };
|
||||
await agentCreation.result;
|
||||
if (outcome === "background") clearConsumedDraft();
|
||||
return outcome;
|
||||
try {
|
||||
await agentCreation.result;
|
||||
} catch (error) {
|
||||
// Once handed off to the workspace draft tab, that tab owns surfacing agent startup errors.
|
||||
if (delivery.outcome === "navigated") return delivery.outcome;
|
||||
throw error;
|
||||
}
|
||||
if (delivery.outcome === "background") clearConsumedDraft();
|
||||
return delivery.outcome;
|
||||
}
|
||||
|
||||
function buildComposerConfig(input: {
|
||||
@@ -1349,6 +1363,7 @@ export function NewWorkspaceScreen({
|
||||
: undefined;
|
||||
const normalizedWorkspace = await createMultiplicityWorkspace({
|
||||
idempotencyKey: creationIdentity.draftId,
|
||||
launchTarget,
|
||||
worktreeSlug: creationIdentity.worktreeSlug,
|
||||
client: connectedClient,
|
||||
isolation: createsWorktree ? "worktree" : "local",
|
||||
@@ -1373,6 +1388,7 @@ export function NewWorkspaceScreen({
|
||||
creationIdentity,
|
||||
creationResult,
|
||||
effectiveIsolation,
|
||||
launchTarget,
|
||||
mergeWorkspaces,
|
||||
queryClient,
|
||||
selectedItem,
|
||||
@@ -1443,7 +1459,9 @@ export function NewWorkspaceScreen({
|
||||
const message = toErrorMessage(error);
|
||||
setPendingAction(null);
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
if (!isStillOnCreateScreen()) {
|
||||
toast.error(message);
|
||||
}
|
||||
}
|
||||
},
|
||||
[
|
||||
@@ -1524,7 +1542,9 @@ export function NewWorkspaceScreen({
|
||||
const message = toErrorMessage(error);
|
||||
setPendingAction(null);
|
||||
setErrorMessage(message);
|
||||
toast.error(message);
|
||||
if (!isStillOnCreateScreen()) {
|
||||
toast.error(message);
|
||||
}
|
||||
}
|
||||
}, [
|
||||
ensureWorkspace,
|
||||
@@ -1662,6 +1682,7 @@ export function NewWorkspaceScreen({
|
||||
clearDraft={noopClearDraft}
|
||||
autoFocus={terminalTakesPrompt}
|
||||
autoFocusKey={launchFocusKey}
|
||||
error={errorMessage}
|
||||
/>
|
||||
) : (
|
||||
<Composer
|
||||
@@ -1693,6 +1714,7 @@ export function NewWorkspaceScreen({
|
||||
autoFocusKey={launchFocusKey}
|
||||
commandDraft={composerState?.commandDraft}
|
||||
agentControls={agentControlsWithDisabled}
|
||||
error={errorMessage}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
@@ -1705,7 +1727,6 @@ export function NewWorkspaceScreen({
|
||||
onImportSession={importSession.open}
|
||||
>
|
||||
{composer}
|
||||
{errorMessage ? <Text style={styles.errorText}>{errorMessage}</Text> : null}
|
||||
</NewWorkspaceLayout>
|
||||
{importSession.sheet}
|
||||
</FileDropZone>
|
||||
@@ -1867,11 +1888,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
color: theme.colors.foreground,
|
||||
},
|
||||
errorText: {
|
||||
fontSize: theme.fontSize.base,
|
||||
color: theme.colors.destructive,
|
||||
lineHeight: 20,
|
||||
},
|
||||
}));
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,9 +12,11 @@ describe("canonical CLI surface", () => {
|
||||
expect(send.opts().behavior).toBe("interrupt");
|
||||
await send.parseAsync(["target", "message", "--behavior", "steer"], { from: "user" });
|
||||
expect(send.opts().behavior).toBe("steer");
|
||||
await send.parseAsync(["target", "message", "--behavior", "queue"], { from: "user" });
|
||||
expect(send.opts().behavior).toBe("queue");
|
||||
send.exitOverride().configureOutput({ writeErr: () => {} });
|
||||
await expect(
|
||||
send.parseAsync(["target", "message", "--behavior", "queue"], { from: "user" }),
|
||||
send.parseAsync(["target", "message", "--behavior", "wait"], { from: "user" }),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildNoWaitResult } from "./send.js";
|
||||
|
||||
const agentId = "11111111-1111-4111-8111-111111111111";
|
||||
|
||||
describe("buildNoWaitResult", () => {
|
||||
it("reports the behavior the host applied to an agent's message", () => {
|
||||
expect(
|
||||
buildNoWaitResult(agentId, {
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "steer",
|
||||
guidance: "The agent is idle, so your message starts a turn now.",
|
||||
}),
|
||||
).toEqual({
|
||||
agentId,
|
||||
status: "queued",
|
||||
activeTurnBehavior: "steer",
|
||||
message: "The agent is idle, so your message starts a turn now.",
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves the behavior out when the host does not report one", () => {
|
||||
expect(buildNoWaitResult(agentId, {})).toEqual({
|
||||
agentId,
|
||||
status: "sent",
|
||||
message: "Message sent, not waiting for completion",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
import { type Command, Option } from "commander";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
import type { AgentActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
import { collectMultiple } from "../../utils/command-options.js";
|
||||
import { connectToDaemon } from "../../utils/client.js";
|
||||
import type { AgentMessageReceipt } from "@getpaseo/client/internal/daemon-client";
|
||||
import type {
|
||||
CommandOptions,
|
||||
SingleResult,
|
||||
@@ -15,6 +16,8 @@ import { extname, resolve } from "node:path";
|
||||
export interface AgentSendResult {
|
||||
agentId: string;
|
||||
status: "queued" | "sent" | "completed" | "timeout" | "permission" | "error";
|
||||
/** What the host applied to an agent's message with a running turn. */
|
||||
activeTurnBehavior?: AgentActiveTurnBehavior;
|
||||
message: string;
|
||||
}
|
||||
|
||||
@@ -29,7 +32,7 @@ export const agentSendSchema: OutputSchema<AgentSendResult> = {
|
||||
};
|
||||
|
||||
export interface AgentSendOptions extends CommandOptions {
|
||||
behavior?: ActiveTurnBehavior;
|
||||
behavior?: AgentActiveTurnBehavior;
|
||||
wait?: boolean;
|
||||
image?: string[];
|
||||
prompt?: string;
|
||||
@@ -47,8 +50,8 @@ export function addSendOptions(cmd: Command): Command {
|
||||
.addOption(
|
||||
new Option(
|
||||
"--behavior <behavior>",
|
||||
"Active-turn behavior (agent default: steer waits for turn end; otherwise: interrupt). An agent's interrupt delivers the messages queued before it first",
|
||||
).choices(["interrupt", "steer"]),
|
||||
"Leave out unless the message cannot wait. From an agent (PASEO_AGENT_ID set): queue (default) waits for the running turn to end, steer joins it, interrupt replaces it. From a person: interrupt (default) or steer",
|
||||
).choices(["queue", "steer", "interrupt"]),
|
||||
)
|
||||
.option("--no-wait", "Return immediately without waiting for completion");
|
||||
}
|
||||
@@ -170,6 +173,22 @@ function buildSendResult(agentIdArg: string, state: SendWaitState): AgentSendRes
|
||||
return { agentId, status: "completed", message: "Agent completed processing the message" };
|
||||
}
|
||||
|
||||
export function buildNoWaitResult(agentId: string, receipt: AgentMessageReceipt): AgentSendResult {
|
||||
return {
|
||||
agentId,
|
||||
status: receipt.deliveryStatus ?? "sent",
|
||||
...(receipt.activeTurnBehavior ? { activeTurnBehavior: receipt.activeTurnBehavior } : {}),
|
||||
message: sendReceiptMessage(receipt),
|
||||
};
|
||||
}
|
||||
|
||||
function sendReceiptMessage(receipt: AgentMessageReceipt): string {
|
||||
if (receipt.deliveryStatus !== "queued") return "Message sent, not waiting for completion";
|
||||
// COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove after 2027-05-22 once daemon
|
||||
// floor >= v0.17.2. Older hosts return no guidance.
|
||||
return receipt.guidance ?? "Message queued for delivery after the current turn ends";
|
||||
}
|
||||
|
||||
export async function runSendCommand(
|
||||
agentIdArg: string,
|
||||
prompt: string | undefined,
|
||||
@@ -204,7 +223,7 @@ export async function runSendCommand(
|
||||
const receipt = await client.sendAgentMessage(agentIdArg, promptInput, {
|
||||
images,
|
||||
sourceAgentId,
|
||||
activeTurnBehavior: options.behavior ?? (sourceAgentId ? "steer" : "interrupt"),
|
||||
activeTurnBehavior: options.behavior,
|
||||
});
|
||||
|
||||
// If --no-wait, return immediately
|
||||
@@ -213,14 +232,7 @@ export async function runSendCommand(
|
||||
|
||||
return {
|
||||
type: "single",
|
||||
data: {
|
||||
agentId: agentIdArg,
|
||||
status: receipt.deliveryStatus ?? "sent",
|
||||
message:
|
||||
receipt.deliveryStatus === "queued"
|
||||
? "Message queued for delivery after two quiet seconds and the current turn ends. An interrupt replaces the turn now, after the messages queued before it"
|
||||
: "Message sent, not waiting for completion",
|
||||
},
|
||||
data: buildNoWaitResult(agentIdArg, receipt),
|
||||
schema: agentSendSchema,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -125,6 +125,7 @@ export class ConnectionSubscriptions extends OwnedSubscriptions {
|
||||
// Protocol support belongs to the installed client. Only browser hosting needs
|
||||
// a resource supplied by the caller. Keep this exhaustive as the protocol evolves.
|
||||
export const DEFAULT_CLIENT_CAPABILITIES = {
|
||||
[CLIENT_CAPS.agentActiveTurnBehaviors]: true,
|
||||
[CLIENT_CAPS.terminalChunkedReplay]: true,
|
||||
[CLIENT_CAPS.binaryChunkingV1]: true,
|
||||
[CLIENT_CAPS.helloRejection]: true,
|
||||
|
||||
@@ -1127,6 +1127,7 @@ test("advertises client capabilities in hello", async () => {
|
||||
clientType: "cli",
|
||||
protocolVersion: 1,
|
||||
capabilities: {
|
||||
agent_active_turn_behaviors: true,
|
||||
all_providers: true,
|
||||
selective_agent_timeline: true,
|
||||
timeline_replacement_invalidation: true,
|
||||
@@ -8828,6 +8829,97 @@ test.each([false, true])(
|
||||
},
|
||||
);
|
||||
|
||||
describe("agent sender active-turn behaviors", () => {
|
||||
async function connect(features: Record<string, boolean>) {
|
||||
const transport = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "agent-behaviors",
|
||||
transportFactory: () => transport.transport,
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
clients.push(client);
|
||||
const connecting = client.connect();
|
||||
transport.triggerOpen({ features: { agentMessageProvenance: true, ...features } });
|
||||
await connecting;
|
||||
return { client, transport };
|
||||
}
|
||||
|
||||
function respond(
|
||||
transport: ReturnType<typeof createMockTransport>,
|
||||
payload: Record<string, unknown> = {},
|
||||
) {
|
||||
const request = parseSentFrame(transport.sent.at(-1));
|
||||
transport.triggerMessage(
|
||||
wrapSessionMessage({
|
||||
type: "send_agent_message_response",
|
||||
payload: {
|
||||
requestId: request.requestId,
|
||||
agentId: "recipient",
|
||||
accepted: true,
|
||||
error: null,
|
||||
...payload,
|
||||
},
|
||||
}),
|
||||
);
|
||||
return request;
|
||||
}
|
||||
|
||||
test("a capable host gets the behavior as asked and returns the applied behavior with guidance", async () => {
|
||||
const { client, transport } = await connect({ agentActiveTurnBehaviors: true });
|
||||
const send = client.sendAgentMessage("recipient", "review", {
|
||||
sourceAgentId: "sender",
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
const request = respond(transport, {
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "steer",
|
||||
guidance: "Steering the running turn.",
|
||||
});
|
||||
expect(request.activeTurnBehavior).toBe("steer");
|
||||
await expect(send).resolves.toEqual({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "steer",
|
||||
guidance: "Steering the running turn.",
|
||||
});
|
||||
});
|
||||
|
||||
test("an older host gets its own agent default for queue and refuses a steer", async () => {
|
||||
const { client, transport } = await connect({});
|
||||
const queued = client.sendAgentMessage("recipient", "review", {
|
||||
sourceAgentId: "sender",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
const request = respond(transport, { deliveryStatus: "queued" });
|
||||
expect("activeTurnBehavior" in request).toBe(false);
|
||||
await expect(queued).resolves.toEqual({ deliveryStatus: "queued" });
|
||||
|
||||
const interrupt = client.sendAgentMessage("recipient", "stop", {
|
||||
sourceAgentId: "sender",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
expect(respond(transport, { deliveryStatus: "queued" }).activeTurnBehavior).toBe("interrupt");
|
||||
await interrupt;
|
||||
|
||||
const sentBefore = transport.sent.length;
|
||||
await expect(
|
||||
client.sendAgentMessage("recipient", "now", {
|
||||
sourceAgentId: "sender",
|
||||
activeTurnBehavior: "steer",
|
||||
}),
|
||||
).rejects.toThrow("Update the Paseo host to steer a running turn from an agent");
|
||||
expect(transport.sent).toHaveLength(sentBefore);
|
||||
});
|
||||
|
||||
test("queue needs an agent sender", async () => {
|
||||
const { client, transport } = await connect({ agentActiveTurnBehaviors: true });
|
||||
await expect(
|
||||
client.sendAgentMessage("recipient", "review", { activeTurnBehavior: "queue" }),
|
||||
).rejects.toThrow('activeTurnBehavior "queue" needs an agent sender');
|
||||
expect(transport.sent).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
test("measures an outbound message in UTF-8 bytes against the daemon's message limit", async () => {
|
||||
const mock = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
|
||||
@@ -47,7 +47,7 @@ import {
|
||||
ShutdownRequestedStatusPayloadSchema,
|
||||
DaemonUpdateResponseSchema,
|
||||
SessionInboundMessageSchema,
|
||||
type ActiveTurnBehavior,
|
||||
type AgentActiveTurnBehavior,
|
||||
type ServerInfoStatusPayload,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { validateWSOutboundMessage } from "@getpaseo/protocol/validation/ws-outbound";
|
||||
@@ -481,13 +481,23 @@ export interface DaemonClientTrace {
|
||||
endSection(): void;
|
||||
}
|
||||
|
||||
/** A queued agent message carries the applied behavior and what happens next. */
|
||||
export interface AgentMessageReceipt {
|
||||
deliveryStatus?: "queued";
|
||||
activeTurnBehavior?: AgentActiveTurnBehavior;
|
||||
guidance?: string;
|
||||
}
|
||||
|
||||
export interface SendMessageOptions {
|
||||
sourceAgentId?: string;
|
||||
sourceAgentServerId?: string;
|
||||
sessionMode?: string;
|
||||
messageId?: string;
|
||||
/** Agent sources wait for turn end unless interrupt is explicit. Human sources default to interrupt. */
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
/**
|
||||
* Agent sources default to queue: wait for the running turn to end. Human sources default to
|
||||
* interrupt and cannot queue.
|
||||
*/
|
||||
activeTurnBehavior?: AgentActiveTurnBehavior;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments?: SendAgentMessageRequest["attachments"];
|
||||
}
|
||||
@@ -4262,7 +4272,7 @@ export class DaemonClient {
|
||||
agentId: string,
|
||||
text: string,
|
||||
options: SendMessageOptions = {},
|
||||
): Promise<{ deliveryStatus?: "queued" }> {
|
||||
): Promise<AgentMessageReceipt> {
|
||||
if (
|
||||
options.sourceAgentId &&
|
||||
this.lastServerInfoMessage?.features?.agentMessageProvenance !== true
|
||||
@@ -4275,6 +4285,7 @@ export class DaemonClient {
|
||||
) {
|
||||
throw new Error("Update the Paseo host to send messages with a qualified agent address.");
|
||||
}
|
||||
const activeTurnBehavior = this.activeTurnBehaviorForHost(options);
|
||||
const requestId = this.createRequestId();
|
||||
const messageId = options.messageId ?? crypto.randomUUID();
|
||||
const message = SessionInboundMessageSchema.parse({
|
||||
@@ -4286,7 +4297,7 @@ export class DaemonClient {
|
||||
sourceAgentServerId: options.sourceAgentServerId,
|
||||
sessionMode: options.sessionMode,
|
||||
...(messageId ? { messageId } : {}),
|
||||
activeTurnBehavior: options.activeTurnBehavior,
|
||||
activeTurnBehavior,
|
||||
images: options.images,
|
||||
attachments: options.attachments,
|
||||
});
|
||||
@@ -4307,14 +4318,39 @@ export class DaemonClient {
|
||||
if (!payload.accepted) {
|
||||
throw new Error(payload.error ?? "sendAgentMessage rejected");
|
||||
}
|
||||
return payload.deliveryStatus ? { deliveryStatus: payload.deliveryStatus } : {};
|
||||
return {
|
||||
...(payload.deliveryStatus ? { deliveryStatus: payload.deliveryStatus } : {}),
|
||||
...(payload.activeTurnBehavior ? { activeTurnBehavior: payload.activeTurnBehavior } : {}),
|
||||
...(payload.guidance ? { guidance: payload.guidance } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The behavior to put on the wire for this host. */
|
||||
private activeTurnBehaviorForHost(
|
||||
options: SendMessageOptions,
|
||||
): AgentActiveTurnBehavior | undefined {
|
||||
const requested = options.activeTurnBehavior;
|
||||
if (!options.sourceAgentId) {
|
||||
if (requested === "queue")
|
||||
throw new Error('activeTurnBehavior "queue" needs an agent sender (sourceAgentId).');
|
||||
return requested;
|
||||
}
|
||||
if (this.lastServerInfoMessage?.features?.agentActiveTurnBehaviors === true) return requested;
|
||||
// COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove after 2027-05-22 once daemon
|
||||
// floor >= v0.17.2. Older hosts reject queue and read an agent's steer as queue, so queue
|
||||
// goes out as the host's own agent default and a real steer needs an update.
|
||||
if (requested === "steer")
|
||||
throw new Error(
|
||||
"Update the Paseo host to steer a running turn from an agent. Leave the behavior out to queue the message, or use interrupt.",
|
||||
);
|
||||
return requested === "interrupt" ? "interrupt" : undefined;
|
||||
}
|
||||
|
||||
async sendMessage(
|
||||
agentId: string,
|
||||
text: string,
|
||||
options?: SendMessageOptions,
|
||||
): Promise<{ deliveryStatus?: "queued" }> {
|
||||
): Promise<AgentMessageReceipt> {
|
||||
return this.sendAgentMessage(agentId, text, options);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,10 @@ export const CLIENT_CAPS = {
|
||||
// update subscriptions, because older apps auto-open a tab for every replicated root agent.
|
||||
backgroundAgents: "background_agents",
|
||||
browserHost: "browser_host",
|
||||
// COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove after 2027-05-22 once client floor >= v0.17.2.
|
||||
// An agent sender's steer means wait-for-turn-end from clients without it, because older
|
||||
// CLIs and connected hosts send an explicit steer for every default agent send.
|
||||
agentActiveTurnBehaviors: "agent_active_turn_behaviors",
|
||||
} as const;
|
||||
|
||||
export type ClientCapability = (typeof CLIENT_CAPS)[keyof typeof CLIENT_CAPS];
|
||||
|
||||
@@ -2,6 +2,8 @@ import {
|
||||
AgentStreamEventPayloadSchema,
|
||||
AgentTimelineEntryPayloadSchema,
|
||||
SendAgentMessageRequestSchema,
|
||||
SendAgentMessageResponseMessageSchema,
|
||||
SendAgentMessageSchema,
|
||||
} from "./messages";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
@@ -29,6 +31,46 @@ describe("send_agent_message_request active-turn behavior", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("agent sender active-turn behaviors", () => {
|
||||
it("accepts queue on a send request and reports the applied behavior in the response", () => {
|
||||
expect(
|
||||
SendAgentMessageRequestSchema.parse({
|
||||
type: "send_agent_message_request",
|
||||
requestId: "request-3",
|
||||
agentId: "agent-1",
|
||||
text: "Report when you are done",
|
||||
sourceAgentId: "parent",
|
||||
activeTurnBehavior: "queue",
|
||||
}).activeTurnBehavior,
|
||||
).toBe("queue");
|
||||
expect(
|
||||
SendAgentMessageResponseMessageSchema.parse({
|
||||
type: "send_agent_message_response",
|
||||
payload: {
|
||||
requestId: "request-3",
|
||||
agentId: "agent-1",
|
||||
accepted: true,
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "queue",
|
||||
guidance: "Queued.",
|
||||
error: null,
|
||||
},
|
||||
}).payload,
|
||||
).toMatchObject({ activeTurnBehavior: "queue", guidance: "Queued." });
|
||||
});
|
||||
|
||||
it("keeps a person's send_agent_message to interrupt and steer", () => {
|
||||
expect(
|
||||
SendAgentMessageSchema.safeParse({
|
||||
type: "send_agent_message",
|
||||
agentId: "agent-1",
|
||||
text: "hello",
|
||||
activeTurnBehavior: "queue",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("canonical timeline turn ID compatibility", () => {
|
||||
it("accepts both new turn-tagged wire rows and legacy rows without IDs", () => {
|
||||
const entry = {
|
||||
|
||||
@@ -1347,6 +1347,9 @@ const ImageAttachmentSchema = z.object({
|
||||
|
||||
export const ActiveTurnBehaviorSchema = z.enum(["interrupt", "steer"]);
|
||||
export type ActiveTurnBehavior = z.infer<typeof ActiveTurnBehaviorSchema>;
|
||||
/** An agent sender may also queue: wait until the recipient's running turn ends. */
|
||||
export const AgentActiveTurnBehaviorSchema = z.enum(["interrupt", "steer", "queue"]);
|
||||
export type AgentActiveTurnBehavior = z.infer<typeof AgentActiveTurnBehaviorSchema>;
|
||||
|
||||
export const SendAgentMessageSchema = z.object({
|
||||
type: z.literal("send_agent_message"),
|
||||
@@ -1524,7 +1527,8 @@ export const SendAgentMessageRequestSchema = z.object({
|
||||
sourceAgentServerId: z.string().min(1).optional(),
|
||||
sessionMode: z.string().optional(),
|
||||
messageId: z.string().optional(), // Client-provided ID for deduplication
|
||||
activeTurnBehavior: ActiveTurnBehaviorSchema.optional(),
|
||||
/** queue needs an agent sender. */
|
||||
activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional(),
|
||||
images: z.array(ImageAttachmentSchema).optional(),
|
||||
attachments: AgentAttachmentsSchema,
|
||||
});
|
||||
@@ -4178,6 +4182,8 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
canonicalSubmittedPrompts: z.boolean().optional(),
|
||||
agentMessageProvenance: z.boolean().optional(),
|
||||
agentMessageBatching: z.boolean().optional(),
|
||||
// COMPAT(agentActiveTurnBehaviors): added in v0.17.2, remove gate after 2027-05-22.
|
||||
agentActiveTurnBehaviors: z.boolean().optional(),
|
||||
// COMPAT(agentTurnIdentity): accept peers that observed pre-release v0.2.6 through 2027-01-31.
|
||||
agentTurnIdentity: z.boolean().optional(),
|
||||
// COMPAT(stableProjectIdentity): added in v0.1.109, remove gate after 2027-01-15.
|
||||
@@ -5523,6 +5529,10 @@ export const SendAgentMessageResponseMessageSchema = z.object({
|
||||
agentId: z.string(),
|
||||
accepted: z.boolean(),
|
||||
deliveryStatus: z.literal("queued").optional(),
|
||||
/** The behavior applied to a queued agent message. */
|
||||
activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional(),
|
||||
/** What happens to a queued agent message, and how the sender can change it. */
|
||||
guidance: z.string().optional(),
|
||||
error: z.string().nullable(),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -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,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"
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.swmansion.enriched.markdown
|
||||
|
||||
import com.facebook.react.bridge.Arguments
|
||||
|
||||
class EnrichedMarkdownTextLayoutManager(
|
||||
private val view: EnrichedMarkdownText,
|
||||
) {
|
||||
private var forceHeightRecalculationCounter = 0
|
||||
|
||||
fun invalidateLayout() {
|
||||
val text = view.text
|
||||
val paint = view.paint
|
||||
val heightChanged = MeasurementStore.store(view.id, text, paint, view.trailingMarginBottomPx())
|
||||
if (!heightChanged) return
|
||||
val stateWrapper = view.stateWrapper ?: return
|
||||
val state = Arguments.createMap()
|
||||
state.putInt("forceHeightRecalculationCounter", ++forceHeightRecalculationCounter)
|
||||
stateWrapper.updateState(state)
|
||||
}
|
||||
|
||||
fun releaseMeasurementStore() {
|
||||
MeasurementStore.release(view.id)
|
||||
}
|
||||
}
|
||||
+390
@@ -0,0 +1,390 @@
|
||||
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.EnrichedMarkdownTextManagerDelegate
|
||||
import com.facebook.react.viewmanagers.EnrichedMarkdownTextManagerInterface
|
||||
import com.facebook.yoga.YogaMeasureMode
|
||||
import com.swmansion.enriched.markdown.spoiler.SpoilerOverlay
|
||||
import com.swmansion.enriched.markdown.utils.common.applyReactBorderProps
|
||||
import com.swmansion.enriched.markdown.utils.common.emitContextMenuItemPress
|
||||
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.TaskListTapUtils
|
||||
import com.swmansion.enriched.markdown.utils.text.interaction.TaskListToggleUtils
|
||||
|
||||
@ReactModule(name = EnrichedMarkdownTextManager.NAME)
|
||||
class EnrichedMarkdownTextManager :
|
||||
SimpleViewManager<EnrichedMarkdownText>(),
|
||||
EnrichedMarkdownTextManagerInterface<EnrichedMarkdownText> {
|
||||
private val mDelegate: ViewManagerDelegate<EnrichedMarkdownText> = EnrichedMarkdownTextManagerDelegate(this)
|
||||
|
||||
override fun getDelegate(): ViewManagerDelegate<EnrichedMarkdownText>? = mDelegate
|
||||
|
||||
override fun getName(): String = NAME
|
||||
|
||||
override fun createViewInstance(reactContext: ThemedReactContext): EnrichedMarkdownText {
|
||||
val view = EnrichedMarkdownText(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 styleConfig = view.markdownStyle
|
||||
val optimizedSuccess =
|
||||
styleConfig != null && TaskListTapUtils.updateTaskListItemCheckedState(view, taskIndex, newChecked, styleConfig)
|
||||
|
||||
if (optimizedSuccess) {
|
||||
emitTaskListItemPress(view, taskIndex, newChecked, itemText)
|
||||
return@setOnTaskListItemPressCallback
|
||||
}
|
||||
|
||||
val currentMarkdown = view.currentMarkdown
|
||||
val updatedMarkdown = TaskListToggleUtils.toggleAtIndex(currentMarkdown, taskIndex, newChecked)
|
||||
view.setMarkdownContent(updatedMarkdown)
|
||||
|
||||
emitTaskListItemPress(view, taskIndex, newChecked, itemText)
|
||||
}
|
||||
|
||||
view.setOnLatexErrorCallback { source, message, displayMode ->
|
||||
emitLatexError(view, source, message, displayMode)
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
override fun onAfterUpdateTransaction(view: EnrichedMarkdownText) {
|
||||
super.onAfterUpdateTransaction(view)
|
||||
view.commitProps()
|
||||
}
|
||||
|
||||
// Replay containerStyle border props the delegate drops (see applyReactBorderProps).
|
||||
override fun updateProperties(
|
||||
view: EnrichedMarkdownText,
|
||||
props: ReactStylesDiffMap,
|
||||
) {
|
||||
super.updateProperties(view, props)
|
||||
applyReactBorderProps(view, props)
|
||||
}
|
||||
|
||||
override fun updateState(
|
||||
view: EnrichedMarkdownText,
|
||||
props: ReactStylesDiffMap?,
|
||||
stateWrapper: StateWrapper?,
|
||||
): Any? {
|
||||
view.stateWrapper = stateWrapper
|
||||
return super.updateState(view, props, stateWrapper)
|
||||
}
|
||||
|
||||
override fun onDropViewInstance(view: EnrichedMarkdownText) {
|
||||
super.onDropViewInstance(view)
|
||||
view.cleanup()
|
||||
MeasurementStore.clearFontScalingSettings(view.id)
|
||||
MeasurementStore.clearBreakStrategy(view.id)
|
||||
view.layoutManager.releaseMeasurementStore()
|
||||
}
|
||||
|
||||
override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> = markdownEventTypeConstants()
|
||||
|
||||
@ReactProp(name = "markdown")
|
||||
override fun setMarkdown(
|
||||
view: EnrichedMarkdownText?,
|
||||
markdown: String?,
|
||||
) {
|
||||
view?.setMarkdownContent(markdown ?: "")
|
||||
}
|
||||
|
||||
@ReactProp(name = "markdownStyle")
|
||||
override fun setMarkdownStyle(
|
||||
view: EnrichedMarkdownText?,
|
||||
style: ReadableMap?,
|
||||
) {
|
||||
view?.setMarkdownStyle(style)
|
||||
}
|
||||
|
||||
@ReactProp(name = "selectable", defaultBoolean = true)
|
||||
override fun setSelectable(
|
||||
view: EnrichedMarkdownText?,
|
||||
selectable: Boolean,
|
||||
) {
|
||||
view?.setIsSelectable(selectable)
|
||||
}
|
||||
|
||||
override fun setSelectionColor(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: Int?,
|
||||
) {
|
||||
view?.setSelectionColor(value)
|
||||
}
|
||||
|
||||
override fun setSelectionHandleColor(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: Int?,
|
||||
) {
|
||||
view?.setSelectionHandleColor(value)
|
||||
}
|
||||
|
||||
@ReactProp(name = "linkRecognition")
|
||||
override fun setLinkRecognition(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: ReadableMap?,
|
||||
) {
|
||||
val recognition = parseLinkRecognition(value)
|
||||
view?.setLinkRegex(recognition.text)
|
||||
view?.setInlineCodeLinkRegex(recognition.inlineCode)
|
||||
}
|
||||
|
||||
@ReactProp(name = "md4cFlags")
|
||||
override fun setMd4cFlags(
|
||||
view: EnrichedMarkdownText?,
|
||||
flags: ReadableMap?,
|
||||
) {
|
||||
view?.setMd4cFlags(parseMd4cFlags(flags))
|
||||
}
|
||||
|
||||
@ReactProp(name = "isGFM", defaultBoolean = false)
|
||||
override fun setIsGFM(
|
||||
view: EnrichedMarkdownText?,
|
||||
isGFM: Boolean,
|
||||
) {
|
||||
view?.setIsGFM(isGFM)
|
||||
}
|
||||
|
||||
@ReactProp(name = "allowFontScaling", defaultBoolean = true)
|
||||
override fun setAllowFontScaling(
|
||||
view: EnrichedMarkdownText?,
|
||||
allowFontScaling: Boolean,
|
||||
) {
|
||||
view?.setAllowFontScaling(allowFontScaling)
|
||||
}
|
||||
|
||||
@ReactProp(name = "maxFontSizeMultiplier", defaultFloat = 0f)
|
||||
override fun setMaxFontSizeMultiplier(
|
||||
view: EnrichedMarkdownText?,
|
||||
maxFontSizeMultiplier: Float,
|
||||
) {
|
||||
view?.setMaxFontSizeMultiplier(maxFontSizeMultiplier)
|
||||
}
|
||||
|
||||
@ReactProp(name = "allowTrailingMargin", defaultBoolean = false)
|
||||
override fun setAllowTrailingMargin(
|
||||
view: EnrichedMarkdownText?,
|
||||
allowTrailingMargin: Boolean,
|
||||
) {
|
||||
view?.setAllowTrailingMargin(allowTrailingMargin)
|
||||
}
|
||||
|
||||
@ReactProp(name = "enableLinkPreview", defaultBoolean = true)
|
||||
override fun setEnableLinkPreview(
|
||||
view: EnrichedMarkdownText?,
|
||||
enableLinkPreview: Boolean,
|
||||
) {
|
||||
// No-op on Android — only used on iOS
|
||||
}
|
||||
|
||||
@ReactProp(name = "enableTaskListItemToggle", defaultBoolean = true)
|
||||
override fun setEnableTaskListItemToggle(
|
||||
view: EnrichedMarkdownText?,
|
||||
enableTaskListItemToggle: Boolean,
|
||||
) {
|
||||
view?.setEnableTaskListItemToggle(enableTaskListItemToggle)
|
||||
}
|
||||
|
||||
@ReactProp(name = "enableImagePress", defaultBoolean = false)
|
||||
override fun setEnableImagePress(
|
||||
view: EnrichedMarkdownText?,
|
||||
enableImagePress: Boolean,
|
||||
) {
|
||||
view?.setEnableImagePress(enableImagePress)
|
||||
}
|
||||
|
||||
@ReactProp(name = "enableBlockContextMenu", defaultBoolean = true)
|
||||
override fun setEnableBlockContextMenu(
|
||||
view: EnrichedMarkdownText?,
|
||||
enableBlockContextMenu: Boolean,
|
||||
) {
|
||||
// No-op: block context menus are rendered by the container component.
|
||||
}
|
||||
|
||||
@ReactProp(name = "enableCodeBlockPress", defaultBoolean = false)
|
||||
override fun setEnableCodeBlockPress(
|
||||
view: EnrichedMarkdownText?,
|
||||
enableCodeBlockPress: Boolean,
|
||||
) {
|
||||
view?.setEnableCodeBlockPress(enableCodeBlockPress)
|
||||
}
|
||||
|
||||
@ReactProp(name = "lineBreakStrategyIOS")
|
||||
override fun setLineBreakStrategyIOS(
|
||||
view: EnrichedMarkdownText?,
|
||||
strategy: String?,
|
||||
) {
|
||||
// No-op on Android — only used on iOS
|
||||
}
|
||||
|
||||
@ReactProp(name = "writingDirection")
|
||||
override fun setWritingDirection(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: String?,
|
||||
) {
|
||||
// No-op on Android — first-strong per-paragraph resolution is the platform default
|
||||
}
|
||||
|
||||
@ReactProp(name = "streamingAnimation", defaultBoolean = false)
|
||||
override fun setStreamingAnimation(
|
||||
view: EnrichedMarkdownText?,
|
||||
streamingAnimation: Boolean,
|
||||
) {
|
||||
view?.setStreamingAnimation(streamingAnimation)
|
||||
}
|
||||
|
||||
@ReactProp(name = "streamingConfig")
|
||||
override fun setStreamingConfig(
|
||||
view: EnrichedMarkdownText?,
|
||||
config: ReadableMap?,
|
||||
) {
|
||||
// No-op — CommonMark mode uses a single text view; table streaming is GFM-only.
|
||||
}
|
||||
|
||||
@ReactProp(name = "spoilerOverlay")
|
||||
override fun setSpoilerOverlay(
|
||||
view: EnrichedMarkdownText?,
|
||||
mode: String?,
|
||||
) {
|
||||
view?.spoilerOverlay = SpoilerOverlay.fromString(mode)
|
||||
}
|
||||
|
||||
@ReactProp(name = "textBreakStrategy")
|
||||
override fun setTextBreakStrategy(
|
||||
view: EnrichedMarkdownText?,
|
||||
strategy: String?,
|
||||
) {
|
||||
view?.setTextBreakStrategy(strategy ?: "highQuality")
|
||||
}
|
||||
|
||||
@ReactProp(name = "numberOfLines", defaultInt = 0)
|
||||
override fun setNumberOfLines(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: Int,
|
||||
) {
|
||||
view?.setMarkdownNumberOfLines(value)
|
||||
}
|
||||
|
||||
@ReactProp(name = "ellipsizeMode")
|
||||
override fun setEllipsizeMode(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: String?,
|
||||
) {
|
||||
view?.setMarkdownEllipsizeMode(value ?: "tail")
|
||||
}
|
||||
|
||||
@ReactProp(name = "linkContextMenuItems")
|
||||
override fun setLinkContextMenuItems(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: ReadableArray?,
|
||||
) {
|
||||
// Link menus are iOS-only for now; onLinkLongPress is the Android hook.
|
||||
}
|
||||
|
||||
@ReactProp(name = "contextMenuItems")
|
||||
override fun setContextMenuItems(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: ReadableArray?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.setContextMenuItems(parseContextMenuItems(value))
|
||||
}
|
||||
|
||||
@ReactProp(name = "imageRequestHeaders")
|
||||
override fun setImageRequestHeaders(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: ReadableArray?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.setImageRequestHeaders(parseImageRequestHeaders(value))
|
||||
}
|
||||
|
||||
@ReactProp(name = "linkPillContent")
|
||||
override fun setLinkPillContent(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: ReadableArray?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.setLinkPillContent(parseLinkPillContent(value))
|
||||
}
|
||||
|
||||
@ReactProp(name = "selectionMenuConfig")
|
||||
override fun setSelectionMenuConfig(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: ReadableMap?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.setSelectionMenuConfig(parseSelectionMenuConfig(value))
|
||||
}
|
||||
|
||||
@ReactProp(name = "accessibilityLabels")
|
||||
override fun setAccessibilityLabels(
|
||||
view: EnrichedMarkdownText?,
|
||||
value: ReadableMap?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.setAccessibilityLabels(parseAccessibilityLabels(value))
|
||||
}
|
||||
|
||||
override fun setPadding(
|
||||
view: EnrichedMarkdownText,
|
||||
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)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val NAME = "EnrichedMarkdownText"
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.swmansion.enriched.markdown
|
||||
|
||||
import com.facebook.react.ReactPackage
|
||||
import com.facebook.react.bridge.NativeModule
|
||||
import com.facebook.react.bridge.ReactApplicationContext
|
||||
import com.facebook.react.uimanager.ViewManager
|
||||
import com.swmansion.enriched.markdown.input.EnrichedMarkdownTextInputManager
|
||||
import java.util.ArrayList
|
||||
|
||||
class EnrichedMarkdownTextPackage : ReactPackage {
|
||||
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
|
||||
val viewManagers: MutableList<ViewManager<*, *>> = ArrayList()
|
||||
viewManagers.add(EnrichedMarkdownTextManager())
|
||||
viewManagers.add(EnrichedMarkdownManager())
|
||||
viewManagers.add(EnrichedMarkdownTextInputManager())
|
||||
return viewManagers
|
||||
}
|
||||
|
||||
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> = emptyList()
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.swmansion.enriched.markdown
|
||||
|
||||
import java.util.concurrent.Executor
|
||||
|
||||
// Keep populated views in step with Fabric geometry when streaming blocks move or collapse.
|
||||
// First mounts retain worker preparation so large history rows do not parse on the UI thread.
|
||||
internal fun dispatchMarkdownRender(hasContent: Boolean, executor: Executor, render: () -> Unit) {
|
||||
if (hasContent) render() else executor.execute(render)
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.swmansion.enriched.markdown
|
||||
|
||||
/** Size-only cache: no views, spans, Contexts or callbacks survive unmount. */
|
||||
internal class MeasurementSizeCache(private val capacity: Int = 512) {
|
||||
data class Key(val markdown: String, val propsHash: Int, val width: Float, val splitTableSegments: Boolean)
|
||||
|
||||
private val sizes = LinkedHashMap<Key, Long>(16, 0.75f, true)
|
||||
|
||||
@Synchronized
|
||||
fun get(key: Key): Long? = sizes[key]
|
||||
|
||||
@Synchronized
|
||||
fun put(key: Key, size: Long) {
|
||||
sizes[key] = size
|
||||
if (sizes.size > capacity) {
|
||||
val oldest = sizes.entries.iterator()
|
||||
oldest.next()
|
||||
oldest.remove()
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun removeMatchingMarkdown(markdown: String) {
|
||||
sizes.keys.removeAll { it.markdown == markdown }
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun clear() {
|
||||
sizes.clear()
|
||||
}
|
||||
}
|
||||
+950
@@ -0,0 +1,950 @@
|
||||
package com.swmansion.enriched.markdown
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Typeface
|
||||
import android.os.Build
|
||||
import android.text.Spannable
|
||||
import android.text.Spanned
|
||||
import android.text.StaticLayout
|
||||
import android.text.TextPaint
|
||||
import android.text.TextUtils.TruncateAt
|
||||
import android.util.Log
|
||||
import com.facebook.react.bridge.ReadableMap
|
||||
import com.facebook.react.uimanager.PixelUtil
|
||||
import com.facebook.yoga.YogaMeasureMode
|
||||
import com.facebook.yoga.YogaMeasureOutput
|
||||
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.segments.BlockquoteContainerView
|
||||
import com.swmansion.enriched.markdown.segments.CodeBlockContainerView
|
||||
import com.swmansion.enriched.markdown.segments.MarkdownSegmentRenderer
|
||||
import com.swmansion.enriched.markdown.segments.RenderedSegment
|
||||
import com.swmansion.enriched.markdown.segments.TableContainerView
|
||||
import com.swmansion.enriched.markdown.segments.splitASTIntoSegments
|
||||
import com.swmansion.enriched.markdown.spans.MarginBottomSpan
|
||||
import com.swmansion.enriched.markdown.spans.MathMeasureRequest
|
||||
import com.swmansion.enriched.markdown.spans.MathMetrics
|
||||
import com.swmansion.enriched.markdown.spans.MathRenderMode
|
||||
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.EllipsizeUtils
|
||||
import com.swmansion.enriched.markdown.utils.common.FeatureFlags
|
||||
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.getArrayOrNull
|
||||
import com.swmansion.enriched.markdown.utils.common.getBooleanOrDefault
|
||||
import com.swmansion.enriched.markdown.utils.common.getIntOrDefault
|
||||
import com.swmansion.enriched.markdown.utils.common.getMapOrNull
|
||||
import com.swmansion.enriched.markdown.utils.common.getStringOrDefault
|
||||
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.text.extensions.replaceMathSpansWithPlaceholders
|
||||
import com.swmansion.enriched.markdown.utils.text.span.prepareWidthAwareSpans
|
||||
import com.swmansion.enriched.markdown.utils.text.view.wrapForInsertionOrderedLayout
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlin.math.ceil
|
||||
|
||||
/**
|
||||
* Manages text measurements for ShadowNode layout.
|
||||
* Parses and renders markdown to Spannable at measure time for accurate height calculation.
|
||||
*/
|
||||
object MeasurementStore {
|
||||
private const val TAG = "MeasurementStore"
|
||||
|
||||
private data class PaintParams(
|
||||
val typeface: Typeface,
|
||||
val fontSize: Float,
|
||||
)
|
||||
|
||||
private data class MeasurementParams(
|
||||
val cachedWidth: Float,
|
||||
val cachedSize: Long,
|
||||
val spannable: CharSequence?,
|
||||
val paintParams: PaintParams,
|
||||
val markdownHash: Int,
|
||||
val sizeKey: MeasurementSizeCache.Key? = null,
|
||||
)
|
||||
|
||||
private val data = ConcurrentHashMap<Int, MeasurementParams>()
|
||||
private val sizes = MeasurementSizeCache()
|
||||
|
||||
// Store font scaling settings per view ID
|
||||
private data class FontScalingSettings(
|
||||
val allowFontScaling: Boolean = true,
|
||||
val maxFontSizeMultiplier: Float = 0f,
|
||||
)
|
||||
|
||||
private val fontScalingSettings = ConcurrentHashMap<Int, FontScalingSettings>()
|
||||
|
||||
private val breakStrategies = ConcurrentHashMap<Int, String>()
|
||||
|
||||
// The measure path and the display TextView resolve the same clamp. 0 means unlimited.
|
||||
private val numberOfLinesByViewId = ConcurrentHashMap<Int, Int>()
|
||||
|
||||
private val ellipsizeModeByViewId = ConcurrentHashMap<Int, String>()
|
||||
|
||||
private val streamingTableModes = ConcurrentHashMap<Int, TableStreamingMode>()
|
||||
|
||||
private val streamingCodeBlockModes = ConcurrentHashMap<Int, CodeBlockStreamingMode>()
|
||||
|
||||
private fun resolveFontScalingSettings(
|
||||
viewId: Int?,
|
||||
props: ReadableMap?,
|
||||
): FontScalingSettings {
|
||||
val stored = viewId?.let { fontScalingSettings[it] }
|
||||
return FontScalingSettings(
|
||||
allowFontScaling =
|
||||
props?.takeIf { it.hasKey("allowFontScaling") }?.getBoolean("allowFontScaling")
|
||||
?: stored?.allowFontScaling
|
||||
?: true,
|
||||
maxFontSizeMultiplier =
|
||||
props?.takeIf { it.hasKey("maxFontSizeMultiplier") }?.getDouble("maxFontSizeMultiplier")?.toFloat()
|
||||
?: stored?.maxFontSizeMultiplier
|
||||
?: 0f,
|
||||
)
|
||||
}
|
||||
|
||||
private val measurePaint = TextPaint()
|
||||
private val measureRenderer = Renderer()
|
||||
|
||||
@Volatile
|
||||
private var lastKnownFontScale: Float = 1.0f
|
||||
|
||||
/** Updates measurement with rendered Spannable. Returns true if height changed. */
|
||||
fun store(
|
||||
id: Int,
|
||||
spannable: CharSequence?,
|
||||
paint: TextPaint,
|
||||
trailingMarginBottomPx: Float = 0f,
|
||||
): Boolean {
|
||||
val cached = data[id]
|
||||
val width = cached?.cachedWidth ?: 0f
|
||||
val oldSize = cached?.cachedSize ?: 0L
|
||||
val existingHash = cached?.markdownHash ?: 0
|
||||
val paintParams = PaintParams(paint.typeface ?: Typeface.DEFAULT, paint.textSize)
|
||||
|
||||
var newSize = measure(width, spannable, paint, id)
|
||||
if (trailingMarginBottomPx > 0f) {
|
||||
newSize =
|
||||
YogaMeasureOutput.make(
|
||||
YogaMeasureOutput.getWidth(newSize),
|
||||
YogaMeasureOutput.getHeight(newSize) + PixelUtil.toDIPFromPixel(trailingMarginBottomPx),
|
||||
)
|
||||
}
|
||||
if (oldSize != newSize) {
|
||||
cached?.sizeKey?.let { sizes.removeMatchingMarkdown(it.markdown) }
|
||||
}
|
||||
data[id] = MeasurementParams(width, newSize, spannable, paintParams, existingHash, cached?.sizeKey)
|
||||
return oldSize != newSize
|
||||
}
|
||||
|
||||
fun release(id: Int) {
|
||||
data.remove(id)
|
||||
numberOfLinesByViewId.remove(id)
|
||||
ellipsizeModeByViewId.remove(id)
|
||||
}
|
||||
|
||||
fun invalidate(id: Int) {
|
||||
data.remove(id)?.sizeKey?.let { sizes.removeMatchingMarkdown(it.markdown) }
|
||||
}
|
||||
|
||||
// Content-box width (px) the measure pass last wrapped at; the display view insets to match (#805).
|
||||
fun contentBoxWidthPx(id: Int): Float? = data[id]?.cachedWidth
|
||||
|
||||
/** Main entry point for ShadowNode measurement. */
|
||||
fun getMeasureById(
|
||||
context: Context,
|
||||
id: Int?,
|
||||
width: Float,
|
||||
widthMode: YogaMeasureMode?,
|
||||
height: Float,
|
||||
heightMode: YogaMeasureMode?,
|
||||
props: ReadableMap?,
|
||||
splitTableSegments: Boolean = false,
|
||||
): Long {
|
||||
// Early exit for empty markdown. Honor widthMode here too: empty content has
|
||||
// zero intrinsic width, so only fill when the width is EXACTLY assigned -
|
||||
// otherwise an empty view would claim all available horizontal space.
|
||||
val markdown = props.getStringOrDefault("markdown", "")
|
||||
if (markdown.isEmpty()) {
|
||||
val emptyWidth = if (widthMode === YogaMeasureMode.EXACTLY) PixelUtil.toDIPFromPixel(width) else 0f
|
||||
return YogaMeasureOutput.make(emptyWidth, 0f)
|
||||
}
|
||||
|
||||
// Resolve the line clamp from props here so the (background) measure pass and
|
||||
// the (main-thread) display TextView never race on the per-viewId cache. Only
|
||||
// overwrite when the key is present so we never clobber the view's value.
|
||||
if (id != null && props != null) {
|
||||
if (props.hasKey("numberOfLines")) {
|
||||
numberOfLinesByViewId[id] = props.getDouble("numberOfLines").toInt()
|
||||
}
|
||||
if (props.hasKey("ellipsizeMode")) {
|
||||
ellipsizeModeByViewId[id] = props.getString("ellipsizeMode") ?: EllipsizeUtils.DEFAULT_MODE
|
||||
}
|
||||
}
|
||||
|
||||
val size = getMeasureByIdInternal(context, id, width, props, splitTableSegments)
|
||||
|
||||
// Honor the Yoga width contract. When the parent assigns an exact width
|
||||
// (flex child, alignItems: stretch, explicit width / width: "100%"), fill it
|
||||
// instead of reporting the content's widest line, which would make the node
|
||||
// hug its content and wrap early. Mirrors RN's TextLayoutManager.calculateWidth;
|
||||
// iOS already does this via ENRMClampMeasuredSize.
|
||||
val resultWidth =
|
||||
if (widthMode === YogaMeasureMode.EXACTLY) {
|
||||
PixelUtil.toDIPFromPixel(width)
|
||||
} else {
|
||||
YogaMeasureOutput.getWidth(size)
|
||||
}
|
||||
|
||||
var resultHeight = YogaMeasureOutput.getHeight(size)
|
||||
if (heightMode === YogaMeasureMode.AT_MOST) {
|
||||
resultHeight = resultHeight.coerceAtMost(PixelUtil.toDIPFromPixel(height))
|
||||
}
|
||||
|
||||
return YogaMeasureOutput.make(resultWidth, resultHeight)
|
||||
}
|
||||
|
||||
fun updateFontScalingSettings(
|
||||
viewId: Int,
|
||||
allowFontScaling: Boolean,
|
||||
maxFontSizeMultiplier: Float,
|
||||
) {
|
||||
val previous = fontScalingSettings[viewId]
|
||||
fontScalingSettings[viewId] = FontScalingSettings(allowFontScaling, maxFontSizeMultiplier)
|
||||
if (previous != null && (previous.allowFontScaling != allowFontScaling || previous.maxFontSizeMultiplier != maxFontSizeMultiplier)) {
|
||||
invalidate(viewId)
|
||||
}
|
||||
}
|
||||
|
||||
fun clearFontScalingSettings(viewId: Int) {
|
||||
fontScalingSettings.remove(viewId)
|
||||
}
|
||||
|
||||
fun updateBreakStrategy(
|
||||
viewId: Int,
|
||||
strategy: String,
|
||||
) {
|
||||
breakStrategies[viewId] = strategy
|
||||
}
|
||||
|
||||
fun clearBreakStrategy(viewId: Int) {
|
||||
breakStrategies.remove(viewId)
|
||||
}
|
||||
|
||||
private fun resolveBreakStrategy(viewId: Int?): Int = BreakStrategyUtils.resolveBreakStrategy(viewId?.let { breakStrategies[it] })
|
||||
|
||||
fun updateNumberOfLines(
|
||||
viewId: Int,
|
||||
numberOfLines: Int,
|
||||
) {
|
||||
numberOfLinesByViewId[viewId] = numberOfLines
|
||||
}
|
||||
|
||||
fun updateEllipsizeMode(
|
||||
viewId: Int,
|
||||
mode: String,
|
||||
) {
|
||||
ellipsizeModeByViewId[viewId] = mode
|
||||
}
|
||||
|
||||
private fun resolveMaxLines(viewId: Int?): Int = viewId?.let { numberOfLinesByViewId[it] } ?: 0
|
||||
|
||||
private fun resolveEllipsize(viewId: Int?): TruncateAt? =
|
||||
EllipsizeUtils.resolveTruncateAt(viewId?.let { ellipsizeModeByViewId[it] } ?: EllipsizeUtils.DEFAULT_MODE)
|
||||
|
||||
fun updateStreamingTableMode(
|
||||
viewId: Int,
|
||||
mode: TableStreamingMode,
|
||||
) {
|
||||
streamingTableModes[viewId] = mode
|
||||
}
|
||||
|
||||
fun clearStreamingTableMode(viewId: Int) {
|
||||
streamingTableModes.remove(viewId)
|
||||
}
|
||||
|
||||
fun updateStreamingCodeBlockMode(
|
||||
viewId: Int,
|
||||
mode: CodeBlockStreamingMode,
|
||||
) {
|
||||
streamingCodeBlockModes[viewId] = mode
|
||||
}
|
||||
|
||||
fun clearStreamingCodeBlockMode(viewId: Int) {
|
||||
streamingCodeBlockModes.remove(viewId)
|
||||
}
|
||||
|
||||
private fun getMeasureByIdInternal(
|
||||
context: Context,
|
||||
id: Int?,
|
||||
width: Float,
|
||||
props: ReadableMap?,
|
||||
splitTableSegments: Boolean,
|
||||
): Long {
|
||||
val (allowFontScaling, maxFontSizeMultiplier) = resolveFontScalingSettings(id, props)
|
||||
|
||||
val fontScale = checkAndUpdateFontScale(context, allowFontScaling, maxFontSizeMultiplier)
|
||||
|
||||
// Use resolved layout settings, including values supplied by native setters.
|
||||
var layoutHash = computePropsHash(props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
layoutHash = 31 * layoutHash + resolveBreakStrategy(id)
|
||||
layoutHash = 31 * layoutHash + resolveMaxLines(id)
|
||||
layoutHash = 31 * layoutHash + (resolveEllipsize(id)?.hashCode() ?: 0)
|
||||
layoutHash = 31 * layoutHash + props.getBooleanOrDefault("streamingAnimation", false).hashCode()
|
||||
layoutHash = 31 * layoutHash + (id?.let { streamingTableModes[it] } ?: TableStreamingMode.PROGRESSIVE).hashCode()
|
||||
layoutHash = 31 * layoutHash + (id?.let { streamingCodeBlockModes[it] } ?: CodeBlockStreamingMode.PROGRESSIVE).hashCode()
|
||||
layoutHash = 31 * layoutHash + context.resources.displayMetrics.density.toBits()
|
||||
val key = MeasurementSizeCache.Key(props.getStringOrDefault("markdown", ""), layoutHash, width, splitTableSegments)
|
||||
val cached = id?.let { data[it] }
|
||||
if (cached?.sizeKey == key) return cached.cachedSize
|
||||
sizes.get(key)?.let { size ->
|
||||
if (id != null) {
|
||||
data[id] = MeasurementParams(width, size, null, PaintParams(Typeface.DEFAULT, 0f), 0, key)
|
||||
}
|
||||
return size
|
||||
}
|
||||
|
||||
val size = measureUncached(context, id, width, props, splitTableSegments, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
sizes.put(key, size)
|
||||
if (id != null) {
|
||||
data.computeIfPresent(id) { _, measured -> measured.copy(sizeKey = key) }
|
||||
}
|
||||
return size
|
||||
}
|
||||
|
||||
private fun measureUncached(
|
||||
context: Context,
|
||||
id: Int?,
|
||||
width: Float,
|
||||
props: ReadableMap?,
|
||||
splitTableSegments: Boolean,
|
||||
allowFontScaling: Boolean,
|
||||
fontScale: Float,
|
||||
maxFontSizeMultiplier: Float,
|
||||
): Long {
|
||||
if (splitTableSegments) {
|
||||
return measureAndCacheSplit(context, id, width, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
}
|
||||
|
||||
val safeId = id ?: return measureAndCache(context, null, width, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
val cached = data[safeId] ?: return measureAndCache(context, safeId, width, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
|
||||
val currentHash = computePropsHash(props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
|
||||
if (cached.markdownHash != currentHash || cached.spannable == null) {
|
||||
return measureAndCache(context, safeId, width, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
}
|
||||
|
||||
// Width changed - re-measure with cached spannable
|
||||
if (cached.cachedWidth != width) {
|
||||
val newSize = measure(width, cached.spannable, cached.paintParams, safeId)
|
||||
data[safeId] = cached.copy(cachedWidth = width, cachedSize = newSize)
|
||||
return newSize
|
||||
}
|
||||
|
||||
return cached.cachedSize
|
||||
}
|
||||
|
||||
private fun computePropsHash(
|
||||
props: ReadableMap?,
|
||||
allowFontScaling: Boolean,
|
||||
fontScale: Float,
|
||||
maxFontSizeMultiplier: Float,
|
||||
): Int {
|
||||
val markdown = props.getStringOrDefault("markdown", "")
|
||||
return computePropsHashForMarkdown(markdown, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
}
|
||||
|
||||
private fun computePropsHashForMarkdown(
|
||||
markdown: String,
|
||||
props: ReadableMap?,
|
||||
allowFontScaling: Boolean,
|
||||
fontScale: Float,
|
||||
maxFontSizeMultiplier: Float,
|
||||
): Int {
|
||||
val styleMap = props.getMapOrNull("markdownStyle")
|
||||
val md4cFlagsMap = props.getMapOrNull("md4cFlags")
|
||||
val allowTrailingMargin = props.getBooleanOrDefault("allowTrailingMargin", false)
|
||||
val imageRequestHeaders = parseImageRequestHeaders(props.getArrayOrNull("imageRequestHeaders"))
|
||||
val linkPillContent = parseLinkPillContent(props.getArrayOrNull("linkPillContent"))
|
||||
var result = markdown.hashCode()
|
||||
// ReadableNativeArray hashes its backing array identity, not its values.
|
||||
result = 31 * result + (styleMap?.toHashMap()?.hashCode() ?: 0)
|
||||
result = 31 * result + (md4cFlagsMap?.toHashMap()?.hashCode() ?: 0)
|
||||
result = 31 * result + props.getBooleanOrDefault("isGFM", false).hashCode()
|
||||
result = 31 * result + props.getStringOrDefault("textBreakStrategy", BreakStrategyUtils.DEFAULT_STRATEGY).hashCode()
|
||||
result = 31 * result + parseLinkRecognition(props.getMapOrNull("linkRecognition")).hashCode()
|
||||
result = 31 * result + fontScale.toBits()
|
||||
result = 31 * result + allowFontScaling.hashCode()
|
||||
result = 31 * result + maxFontSizeMultiplier.toBits()
|
||||
result = 31 * result + allowTrailingMargin.hashCode()
|
||||
result = 31 * result + imageRequestHeaders.hashCode()
|
||||
result = 31 * result + linkPillContent.hashCode()
|
||||
result = 31 * result + props.getIntOrDefault("numberOfLines", 0)
|
||||
result = 31 * result + props.getStringOrDefault("ellipsizeMode", EllipsizeUtils.DEFAULT_MODE).hashCode()
|
||||
return result
|
||||
}
|
||||
|
||||
private fun checkAndUpdateFontScale(
|
||||
context: Context,
|
||||
allowFontScaling: Boolean,
|
||||
maxFontSizeMultiplier: Float,
|
||||
): Float {
|
||||
if (!allowFontScaling) {
|
||||
// Clear cache if we switched from scaling to non-scaling
|
||||
if (lastKnownFontScale != 1.0f) {
|
||||
lastKnownFontScale = 1.0f
|
||||
data.clear()
|
||||
sizes.clear()
|
||||
}
|
||||
return 1.0f
|
||||
}
|
||||
|
||||
var currentFontScale = context.resources.configuration.fontScale
|
||||
|
||||
if (maxFontSizeMultiplier >= 1.0f && currentFontScale > maxFontSizeMultiplier) {
|
||||
currentFontScale = maxFontSizeMultiplier
|
||||
}
|
||||
if (currentFontScale != lastKnownFontScale) {
|
||||
lastKnownFontScale = currentFontScale
|
||||
data.clear()
|
||||
sizes.clear()
|
||||
}
|
||||
return currentFontScale
|
||||
}
|
||||
|
||||
private fun measureAndCache(
|
||||
context: Context,
|
||||
id: Int?,
|
||||
width: Float,
|
||||
props: ReadableMap?,
|
||||
allowFontScaling: Boolean,
|
||||
fontScale: Float,
|
||||
maxFontSizeMultiplier: Float,
|
||||
): Long {
|
||||
// 1. Extract Props & Setup
|
||||
val markdown = props.getStringOrDefault("markdown", "")
|
||||
val styleMap = props.getMapOrNull("markdownStyle")
|
||||
val md4cFlags =
|
||||
Md4cFlags(
|
||||
underline = props.getMapOrNull("md4cFlags").getBooleanOrDefault("underline", false),
|
||||
latexMath = FeatureFlags.IS_MATH_ENABLED && props.getMapOrNull("md4cFlags").getBooleanOrDefault("latexMath", true),
|
||||
superscript = props.getMapOrNull("md4cFlags").getBooleanOrDefault("superscript", false),
|
||||
subscript = props.getMapOrNull("md4cFlags").getBooleanOrDefault("subscript", false),
|
||||
highlight = props.getMapOrNull("md4cFlags").getBooleanOrDefault("highlight", false),
|
||||
hardSoftBreaks = props.getMapOrNull("md4cFlags").getBooleanOrDefault("hardSoftBreaks", false),
|
||||
preserveBlankLines = props.getMapOrNull("md4cFlags").getBooleanOrDefault("preserveBlankLines", false),
|
||||
admonitions = props.getMapOrNull("md4cFlags").getBooleanOrDefault("admonitions", true),
|
||||
)
|
||||
val isGFM = props.getBooleanOrDefault("isGFM", false)
|
||||
|
||||
val fontSize = getInitialFontSize(styleMap, context, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
val propsHash = computePropsHash(props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
|
||||
// 2. Render & Measure
|
||||
measurePaint.textSize = fontSize
|
||||
val imageRequestHeaders = parseImageRequestHeaders(props.getArrayOrNull("imageRequestHeaders"))
|
||||
val linkRecognition = parseLinkRecognition(props.getMapOrNull("linkRecognition"))
|
||||
val spannable =
|
||||
tryRenderMarkdown(
|
||||
markdown,
|
||||
styleMap,
|
||||
context,
|
||||
md4cFlags,
|
||||
isGFM,
|
||||
allowFontScaling,
|
||||
maxFontSizeMultiplier,
|
||||
imageRequestHeaders,
|
||||
parseLinkPillContent(props.getArrayOrNull("linkPillContent")),
|
||||
linkRecognition.text,
|
||||
linkRecognition.inlineCode,
|
||||
)
|
||||
spannable?.replaceMathSpansWithPlaceholders(context)
|
||||
val textToMeasure = spannable ?: markdown
|
||||
val (size, _) = measureWithLayout(width, textToMeasure, measurePaint, id)
|
||||
|
||||
// 3. Calculate Margin
|
||||
val allowTrailingMargin = props.getBooleanOrDefault("allowTrailingMargin", false)
|
||||
val marginBottom =
|
||||
if (allowTrailingMargin && spannable != null) {
|
||||
PixelUtil.toDIPFromPixel(measureRenderer.getLastElementMarginBottom())
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
|
||||
// 4. Finalize Height
|
||||
val currentWidth = YogaMeasureOutput.getWidth(size)
|
||||
val currentHeight = YogaMeasureOutput.getHeight(size)
|
||||
val adjustedSize = YogaMeasureOutput.make(currentWidth, currentHeight + marginBottom)
|
||||
|
||||
if (id != null) {
|
||||
data[id] = MeasurementParams(width, adjustedSize, textToMeasure, PaintParams(Typeface.DEFAULT, fontSize), propsHash)
|
||||
}
|
||||
|
||||
return adjustedSize
|
||||
}
|
||||
|
||||
private fun measureAndCacheSplit(
|
||||
context: Context,
|
||||
id: Int?,
|
||||
width: Float,
|
||||
props: ReadableMap?,
|
||||
allowFontScaling: Boolean,
|
||||
fontScale: Float,
|
||||
maxFontSizeMultiplier: Float,
|
||||
): Long {
|
||||
val isStreaming = props.getBooleanOrDefault("streamingAnimation", false)
|
||||
|
||||
val rawMarkdown = props.getStringOrDefault("markdown", "")
|
||||
val tableMode =
|
||||
if (isStreaming) {
|
||||
id?.let {
|
||||
streamingTableModes[it]
|
||||
} ?: TableStreamingMode.PROGRESSIVE
|
||||
} else {
|
||||
TableStreamingMode.PROGRESSIVE
|
||||
}
|
||||
val codeBlockMode =
|
||||
if (isStreaming) {
|
||||
id?.let {
|
||||
streamingCodeBlockModes[it]
|
||||
} ?: CodeBlockStreamingMode.PROGRESSIVE
|
||||
} else {
|
||||
CodeBlockStreamingMode.PROGRESSIVE
|
||||
}
|
||||
val markdown =
|
||||
if (isStreaming) {
|
||||
StreamingMarkdownFilter.renderableMarkdownForStreaming(rawMarkdown, tableMode, codeBlockMode).markdown
|
||||
} else {
|
||||
rawMarkdown
|
||||
}
|
||||
val propsHash = computePropsHashForMarkdown(markdown, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
|
||||
// Streaming shortcut: reuse cached size when the filtered content and
|
||||
// width are unchanged. When the filter output changes (e.g. a table
|
||||
// becomes complete), the hash differs and we fall through to full measure.
|
||||
if (isStreaming && id != null) {
|
||||
val cached = data[id]
|
||||
if (cached != null && cached.cachedWidth == width && cached.markdownHash == propsHash) {
|
||||
return cached.cachedSize
|
||||
}
|
||||
}
|
||||
val styleMap =
|
||||
props.getMapOrNull("markdownStyle")
|
||||
?: return YogaMeasureOutput.make(PixelUtil.toDIPFromPixel(width), 0f)
|
||||
|
||||
val md4cFlags =
|
||||
Md4cFlags(
|
||||
underline = props.getMapOrNull("md4cFlags").getBooleanOrDefault("underline", false),
|
||||
latexMath = FeatureFlags.IS_MATH_ENABLED && props.getMapOrNull("md4cFlags").getBooleanOrDefault("latexMath", true),
|
||||
superscript = props.getMapOrNull("md4cFlags").getBooleanOrDefault("superscript", false),
|
||||
subscript = props.getMapOrNull("md4cFlags").getBooleanOrDefault("subscript", false),
|
||||
highlight = props.getMapOrNull("md4cFlags").getBooleanOrDefault("highlight", false),
|
||||
hardSoftBreaks = props.getMapOrNull("md4cFlags").getBooleanOrDefault("hardSoftBreaks", false),
|
||||
preserveBlankLines = props.getMapOrNull("md4cFlags").getBooleanOrDefault("preserveBlankLines", false),
|
||||
admonitions = props.getMapOrNull("md4cFlags").getBooleanOrDefault("admonitions", true),
|
||||
)
|
||||
val isGFM = props.getBooleanOrDefault("isGFM", true)
|
||||
val allowTrailingMargin = props.getBooleanOrDefault("allowTrailingMargin", false)
|
||||
val fontSize = getInitialFontSize(styleMap, context, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
|
||||
val linkRecognition = parseLinkRecognition(props.getMapOrNull("linkRecognition"))
|
||||
|
||||
return try {
|
||||
val ast =
|
||||
Parser.shared.parseMarkdown(
|
||||
markdown,
|
||||
md4cFlags,
|
||||
isGFM,
|
||||
linkRecognition.text,
|
||||
linkRecognition.inlineCode,
|
||||
)
|
||||
?: return YogaMeasureOutput.make(PixelUtil.toDIPFromPixel(width), 0f)
|
||||
|
||||
val style = StyleConfig(styleMap, context, allowFontScaling, maxFontSizeMultiplier)
|
||||
style.imageRequestHeaders = parseImageRequestHeaders(props.getArrayOrNull("imageRequestHeaders"))
|
||||
style.linkPillContent = parseLinkPillContent(props.getArrayOrNull("linkPillContent"))
|
||||
val segments = splitASTIntoSegments(ast)
|
||||
val renderedSegments = MarkdownSegmentRenderer.render(segments, style, context, null, null)
|
||||
|
||||
val mathHeightByIndex = HashMap<Int, Float>()
|
||||
val mathSegmentIndices = mutableListOf<Int>()
|
||||
val mathRequests = mutableListOf<MathMeasureRequest>()
|
||||
for ((i, segment) in renderedSegments.withIndex()) {
|
||||
if (segment is RenderedSegment.Math) {
|
||||
mathSegmentIndices.add(i)
|
||||
mathRequests.add(
|
||||
MathMeasureRequest(
|
||||
fontSize = style.mathStyle.fontSize,
|
||||
latex = segment.latex,
|
||||
mode = MathRenderMode.Display,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (mathRequests.isNotEmpty()) {
|
||||
val mathResults = measureMathOnMainThread(context, mathRequests)
|
||||
for (i in mathSegmentIndices.indices) {
|
||||
val metrics = mathResults[i]
|
||||
mathHeightByIndex[mathSegmentIndices[i]] =
|
||||
ceil(metrics.ascent + metrics.descent).toInt() + (style.mathStyle.padding * 2)
|
||||
}
|
||||
}
|
||||
|
||||
val widthPx = ceil(width).toInt().coerceAtLeast(1)
|
||||
val lastIndex = renderedSegments.lastIndex
|
||||
var totalHeightPx = 0f
|
||||
var maxContentWidthPx = 0f
|
||||
|
||||
for ((index, segment) in renderedSegments.withIndex()) {
|
||||
val isLastSegment = index == lastIndex
|
||||
val includeBottomMargin = if (isLastSegment) allowTrailingMargin else true
|
||||
|
||||
when (segment) {
|
||||
is RenderedSegment.Text -> {
|
||||
segment.styledText.replaceMathSpansWithPlaceholders(context)
|
||||
|
||||
val layout = createStaticLayout(segment.styledText, fontSize, widthPx, id)
|
||||
totalHeightPx += layout.height
|
||||
|
||||
val segmentMaxLineWidth = (0 until layout.lineCount).maxOfOrNull { layout.getLineWidth(it) } ?: 0f
|
||||
maxContentWidthPx = maxOf(maxContentWidthPx, ceil(segmentMaxLineWidth))
|
||||
|
||||
if (includeBottomMargin) {
|
||||
totalHeightPx += segment.lastElementMarginBottom
|
||||
}
|
||||
}
|
||||
|
||||
is RenderedSegment.Table -> {
|
||||
totalHeightPx += style.tableStyle.marginTop
|
||||
totalHeightPx += TableContainerView.measureTableNodeHeight(segment.node, style, context)
|
||||
maxContentWidthPx = width
|
||||
if (includeBottomMargin) {
|
||||
totalHeightPx += style.tableStyle.marginBottom
|
||||
}
|
||||
}
|
||||
|
||||
is RenderedSegment.Math -> {
|
||||
totalHeightPx += style.mathStyle.marginTop
|
||||
totalHeightPx += mathHeightByIndex[index] ?: 0f
|
||||
maxContentWidthPx = width
|
||||
if (includeBottomMargin) {
|
||||
totalHeightPx += style.mathStyle.marginBottom
|
||||
}
|
||||
}
|
||||
|
||||
is RenderedSegment.CodeBlock -> {
|
||||
totalHeightPx += style.codeBlockStyle.marginTop
|
||||
totalHeightPx += CodeBlockContainerView.measureCodeBlockNodeHeight(segment.node, style, context, width)
|
||||
maxContentWidthPx = width
|
||||
if (includeBottomMargin) {
|
||||
totalHeightPx += style.codeBlockStyle.marginBottom
|
||||
}
|
||||
}
|
||||
|
||||
is RenderedSegment.Blockquote -> {
|
||||
totalHeightPx += style.blockquoteStyle.marginTop
|
||||
totalHeightPx += BlockquoteContainerView.measureBlockquoteNodeHeight(segment.node, style, context, width)
|
||||
maxContentWidthPx = width
|
||||
if (includeBottomMargin) {
|
||||
totalHeightPx += style.blockquoteStyle.marginBottom
|
||||
}
|
||||
}
|
||||
|
||||
is RenderedSegment.Video -> {
|
||||
totalHeightPx += style.videoStyle.marginTop
|
||||
totalHeightPx += width / style.videoStyle.resolvedAspectRatio
|
||||
maxContentWidthPx = width
|
||||
if (includeBottomMargin) {
|
||||
totalHeightPx += style.videoStyle.marginBottom
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val totalHeightDip = PixelUtil.toDIPFromPixel(totalHeightPx)
|
||||
val measuredWidthDip = PixelUtil.toDIPFromPixel(maxContentWidthPx).coerceAtMost(PixelUtil.toDIPFromPixel(width))
|
||||
val result = YogaMeasureOutput.make(measuredWidthDip, totalHeightDip)
|
||||
|
||||
if (id != null) {
|
||||
data[id] = MeasurementParams(width, result, null, PaintParams(Typeface.DEFAULT, fontSize), propsHash)
|
||||
}
|
||||
result
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Split measurement failed, falling back", e)
|
||||
measureAndCache(context, id, width, props, allowFontScaling, fontScale, maxFontSizeMultiplier)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun createStaticLayout(
|
||||
text: CharSequence,
|
||||
fontSize: Float,
|
||||
widthPx: Int,
|
||||
viewId: Int?,
|
||||
): StaticLayout {
|
||||
measurePaint.textSize = fontSize
|
||||
prepareWidthAwareSpans(text, widthPx)
|
||||
val measuredText = wrapForInsertionOrderedLayout(text)
|
||||
return StaticLayout.Builder
|
||||
.obtain(measuredText, 0, measuredText.length, measurePaint, widthPx)
|
||||
.setIncludePad(false)
|
||||
.setLineSpacing(0f, 1f)
|
||||
.apply {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
@Suppress("WrongConstant")
|
||||
setBreakStrategy(resolveBreakStrategy(viewId))
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
setUseLineSpacingFromFallbacks(true)
|
||||
}
|
||||
}.build()
|
||||
}
|
||||
|
||||
private fun tryRenderMarkdown(
|
||||
markdown: String,
|
||||
styleMap: ReadableMap?,
|
||||
context: Context,
|
||||
md4cFlags: Md4cFlags,
|
||||
isGFM: Boolean,
|
||||
allowFontScaling: Boolean,
|
||||
maxFontSizeMultiplier: Float,
|
||||
imageRequestHeaders: Map<String, String> = emptyMap(),
|
||||
linkPillContent: Map<String, LinkPillContent> = emptyMap(),
|
||||
linkRegex: LinkRegexConfig? = null,
|
||||
inlineCodeLinkRegex: LinkRegexConfig? = null,
|
||||
): Spannable? {
|
||||
if (styleMap == null) return null
|
||||
|
||||
return try {
|
||||
val ast = Parser.shared.parseMarkdown(markdown, md4cFlags, isGFM, linkRegex, inlineCodeLinkRegex) ?: return null
|
||||
val style = StyleConfig(styleMap, context, allowFontScaling, maxFontSizeMultiplier)
|
||||
style.imageRequestHeaders = imageRequestHeaders
|
||||
style.linkPillContent = linkPillContent
|
||||
measureRenderer.configure(style, context)
|
||||
measureRenderer.renderDocument(ast, null)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to render markdown for measurement, falling back to raw text", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun getInitialFontSize(
|
||||
styleMap: ReadableMap?,
|
||||
context: Context,
|
||||
allowFontScaling: Boolean,
|
||||
fontScale: Float,
|
||||
maxFontSizeMultiplier: Float,
|
||||
): Float {
|
||||
val fontSizeSp = styleMap?.getMap("paragraph")?.getDouble("fontSize")?.toFloat() ?: 16f
|
||||
val density = context.resources.displayMetrics.density
|
||||
|
||||
if (!allowFontScaling) {
|
||||
return ceil(fontSizeSp * density)
|
||||
}
|
||||
|
||||
val cappedFontScale =
|
||||
if (maxFontSizeMultiplier >= 1.0f && fontScale > maxFontSizeMultiplier) {
|
||||
maxFontSizeMultiplier
|
||||
} else {
|
||||
fontScale
|
||||
}
|
||||
return ceil(fontSizeSp * cappedFontScale * density)
|
||||
}
|
||||
|
||||
private fun measure(
|
||||
maxWidth: Float,
|
||||
text: CharSequence?,
|
||||
paintParams: PaintParams,
|
||||
viewId: Int?,
|
||||
): Long {
|
||||
measurePaint.reset()
|
||||
measurePaint.typeface = paintParams.typeface
|
||||
measurePaint.textSize = paintParams.fontSize
|
||||
return measure(maxWidth, text, measurePaint, viewId)
|
||||
}
|
||||
|
||||
private fun measure(
|
||||
maxWidth: Float,
|
||||
text: CharSequence?,
|
||||
paint: TextPaint,
|
||||
viewId: Int?,
|
||||
): Long {
|
||||
val content = text ?: ""
|
||||
val safeWidth = ceil(maxWidth).toInt().coerceAtLeast(1)
|
||||
prepareWidthAwareSpans(content, safeWidth)
|
||||
val measuredText = wrapForInsertionOrderedLayout(content)
|
||||
|
||||
val builder =
|
||||
StaticLayout.Builder
|
||||
.obtain(measuredText, 0, measuredText.length, paint, safeWidth)
|
||||
.setIncludePad(false)
|
||||
.setLineSpacing(0f, 1f)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
@Suppress("WrongConstant")
|
||||
builder.setBreakStrategy(resolveBreakStrategy(viewId))
|
||||
}
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
builder.setUseLineSpacingFromFallbacks(true)
|
||||
}
|
||||
|
||||
applyLineLimit(builder, viewId)
|
||||
|
||||
val layout = builder.build()
|
||||
val visibleLineCount = visibleLineCount(layout, viewId)
|
||||
val measuredHeight = truncatedHeight(layout, visibleLineCount, content)
|
||||
|
||||
// Calculate actual content width (widest visible line)
|
||||
val measuredWidth = (0 until visibleLineCount).maxOfOrNull { layout.getLineWidth(it) } ?: 0f
|
||||
|
||||
return YogaMeasureOutput.make(
|
||||
PixelUtil.toDIPFromPixel(ceil(measuredWidth)),
|
||||
PixelUtil.toDIPFromPixel(measuredHeight),
|
||||
)
|
||||
}
|
||||
|
||||
// Applies the per-view numberOfLines / ellipsizeMode clamp to a builder, matching
|
||||
// RN's TextLayoutManager.buildLayout: only when a line limit is set.
|
||||
private fun applyLineLimit(
|
||||
builder: StaticLayout.Builder,
|
||||
viewId: Int?,
|
||||
) {
|
||||
val maxLines = resolveMaxLines(viewId)
|
||||
if (maxLines > 0) {
|
||||
builder.setMaxLines(maxLines).setEllipsize(resolveEllipsize(viewId))
|
||||
}
|
||||
}
|
||||
|
||||
private fun visibleLineCount(
|
||||
layout: StaticLayout,
|
||||
viewId: Int?,
|
||||
): Int {
|
||||
val maxLines = resolveMaxLines(viewId)
|
||||
return if (maxLines > 0) minOf(maxLines, layout.lineCount) else layout.lineCount
|
||||
}
|
||||
|
||||
private fun truncatedHeight(
|
||||
layout: StaticLayout,
|
||||
visibleLineCount: Int,
|
||||
text: CharSequence,
|
||||
): Float {
|
||||
if (visibleLineCount <= 0) return 0f
|
||||
val lastLine = visibleLineCount - 1
|
||||
val bottom = layout.getLineBottom(lastLine).toFloat()
|
||||
return (bottom - measureLeakedTrailingMargin(layout, lastLine, text)).coerceAtLeast(0f)
|
||||
}
|
||||
|
||||
// When we clamp the text mid-paragraph, drop the trailing block margin that Android
|
||||
// bakes into the truncated last line (only when content follows, like MarginBottomSpan).
|
||||
private fun measureLeakedTrailingMargin(
|
||||
layout: StaticLayout,
|
||||
lastLine: Int,
|
||||
text: CharSequence,
|
||||
): Float {
|
||||
val spanned = text as? Spanned ?: return 0f
|
||||
val lineStart = layout.getLineStart(lastLine)
|
||||
val lineEnd = layout.getLineEnd(lastLine)
|
||||
if (lineEnd <= lineStart || lineEnd < 1 || text[lineEnd - 1] != '\n') return 0f
|
||||
if (!hasContentAfter(text, lineEnd)) return 0f
|
||||
val trailing =
|
||||
spanned
|
||||
.getSpans(lineStart, lineEnd, MarginBottomSpan::class.java)
|
||||
.firstOrNull { spanned.getSpanEnd(it) == lineEnd } ?: return 0f
|
||||
return trailing.marginBottom.toInt().toFloat()
|
||||
}
|
||||
|
||||
private fun hasContentAfter(
|
||||
text: CharSequence,
|
||||
pos: Int,
|
||||
): Boolean {
|
||||
if (pos >= text.length) return false
|
||||
if (text[pos] == '\n') {
|
||||
val nextPos = pos + 1
|
||||
if (nextPos >= text.length) return false
|
||||
return text[nextPos] != '\n'
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures text and returns both the size and the layout for calculating last line descent.
|
||||
*/
|
||||
private fun measureWithLayout(
|
||||
maxWidth: Float,
|
||||
text: CharSequence?,
|
||||
paint: TextPaint,
|
||||
viewId: Int?,
|
||||
): Pair<Long, StaticLayout> {
|
||||
val content = text ?: ""
|
||||
val widthPx = ceil(maxWidth).toInt().coerceAtLeast(1)
|
||||
prepareWidthAwareSpans(content, widthPx)
|
||||
val measuredText = wrapForInsertionOrderedLayout(content)
|
||||
|
||||
val layout =
|
||||
StaticLayout.Builder
|
||||
.obtain(measuredText, 0, measuredText.length, paint, widthPx)
|
||||
.setIncludePad(false)
|
||||
.setLineSpacing(0f, 1f)
|
||||
.apply {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
@Suppress("WrongConstant")
|
||||
setBreakStrategy(resolveBreakStrategy(viewId))
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
setUseLineSpacingFromFallbacks(true)
|
||||
}
|
||||
applyLineLimit(this, viewId)
|
||||
}.build()
|
||||
|
||||
val visibleLineCount = visibleLineCount(layout, viewId)
|
||||
|
||||
// Find the widest visible line to get the actual content width
|
||||
val maxLineWidth =
|
||||
(0 until visibleLineCount)
|
||||
.maxOfOrNull { layout.getLineWidth(it) } ?: 0f
|
||||
|
||||
val size =
|
||||
YogaMeasureOutput.make(
|
||||
PixelUtil.toDIPFromPixel(ceil(maxLineWidth)),
|
||||
PixelUtil.toDIPFromPixel(truncatedHeight(layout, visibleLineCount, content)),
|
||||
)
|
||||
|
||||
return size to layout
|
||||
}
|
||||
|
||||
private fun measureMathOnMainThread(
|
||||
context: Context,
|
||||
requests: List<MathMeasureRequest>,
|
||||
): List<MathMetrics> {
|
||||
if (!FeatureFlags.IS_MATH_ENABLED || requests.isEmpty()) {
|
||||
return requests.map { estimateMathFallback(it) }
|
||||
}
|
||||
return try {
|
||||
val mathMeasureHelperClass = Class.forName("com.swmansion.enriched.markdown.spans.MathMeasureHelper")
|
||||
val method = mathMeasureHelperClass.getMethod("measure", Context::class.java, List::class.java)
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
method.invoke(null, context, requests) as List<MathMetrics>
|
||||
} catch (_: Exception) {
|
||||
requests.map { estimateMathFallback(it) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun estimateMathFallback(request: MathMeasureRequest): MathMetrics {
|
||||
val estimatedHeight = request.fontSize * 1.4f
|
||||
return MathMetrics(
|
||||
width =
|
||||
(request.fontSize * request.latex.length * 0.5f)
|
||||
.coerceIn(request.fontSize, request.fontSize * 20f)
|
||||
.toInt(),
|
||||
ascent = estimatedHeight * 0.7f,
|
||||
descent = estimatedHeight * 0.3f,
|
||||
)
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.swmansion.enriched.markdown.accessibility
|
||||
|
||||
data class AccessibilityLabels(
|
||||
val bulletPoint: String = "",
|
||||
val nestedBulletPoint: String = "",
|
||||
val orderedItem: String = "",
|
||||
val nestedOrderedItem: String = "",
|
||||
val blockquote: String = "",
|
||||
val nestedBlockquote: String = "",
|
||||
val tableRow: String = "",
|
||||
val mathEquation: String = "",
|
||||
val rotorHeadings: String = "",
|
||||
val rotorLinks: String = "",
|
||||
val rotorImages: String = "",
|
||||
)
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.swmansion.enriched.markdown.accessibility
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Rect
|
||||
import android.util.AttributeSet
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import androidx.appcompat.widget.AppCompatTextView
|
||||
import com.swmansion.enriched.markdown.spans.LinkPillSpan
|
||||
import com.swmansion.enriched.markdown.utils.text.span.prepareWidthAwareSpans
|
||||
|
||||
/** AppCompatTextView with built-in TalkBack support via MarkdownAccessibilityHelper. */
|
||||
abstract class AccessibleMarkdownTextView
|
||||
@JvmOverloads
|
||||
constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
defStyleAttr: Int = 0,
|
||||
) : AppCompatTextView(context, attrs, defStyleAttr) {
|
||||
val accessibilityHelper = MarkdownAccessibilityHelper(this)
|
||||
|
||||
override fun setText(
|
||||
text: CharSequence?,
|
||||
type: BufferType?,
|
||||
) {
|
||||
// Prime pills before the layout for the new text is built, and register for icons
|
||||
// that load later. Runs from the TextView constructor too: use nothing initialized after it.
|
||||
val contentWidth = width - compoundPaddingLeft - compoundPaddingRight
|
||||
if (contentWidth > 0) prepareWidthAwareSpans(text, contentWidth, includeImages = false)
|
||||
LinkPillSpan.registerView(text, this)
|
||||
super.setText(text, type)
|
||||
}
|
||||
|
||||
override fun onMeasure(
|
||||
widthMeasureSpec: Int,
|
||||
heightMeasureSpec: Int,
|
||||
) {
|
||||
if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED) {
|
||||
val width = (MeasureSpec.getSize(widthMeasureSpec) - compoundPaddingLeft - compoundPaddingRight).coerceAtLeast(1)
|
||||
// TextView keeps its layout when the new width still fits the old lines.
|
||||
if (prepareWidthAwareSpans(text, width, includeImages = false) && layout != null) dropTextLayout()
|
||||
}
|
||||
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the next measure build a fresh text layout. TextView exposes no direct way:
|
||||
* re-setting the text would copy it and clear the selection, while setting the break
|
||||
* strategy, even to its current value, discards the layout and nothing else.
|
||||
*/
|
||||
private fun dropTextLayout() {
|
||||
breakStrategy = breakStrategy
|
||||
}
|
||||
|
||||
override fun dispatchHoverEvent(event: MotionEvent): Boolean =
|
||||
accessibilityHelper.dispatchHoverEvent(event) || super.dispatchHoverEvent(event)
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean = accessibilityHelper.dispatchKeyEvent(event) || super.dispatchKeyEvent(event)
|
||||
|
||||
override fun onFocusChanged(
|
||||
gainFocus: Boolean,
|
||||
direction: Int,
|
||||
previouslyFocusedRect: Rect?,
|
||||
) {
|
||||
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect)
|
||||
accessibilityHelper.onFocusChanged(gainFocus, direction, previouslyFocusedRect)
|
||||
}
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
// Before super, and here rather than in a ViewManager's
|
||||
// onDropViewInstance: getViewTreeObserver() returns the WINDOW's observer
|
||||
// only while the view is attached. Once detached it hands back the view's
|
||||
// own floating observer, so a removal then would target the wrong
|
||||
// observer and leave the listener on the window.
|
||||
accessibilityHelper.cleanup()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
}
|
||||
+576
@@ -0,0 +1,576 @@
|
||||
package com.swmansion.enriched.markdown.accessibility
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.os.Bundle
|
||||
import android.text.Layout
|
||||
import android.text.Spanned
|
||||
import android.view.View
|
||||
import android.view.ViewTreeObserver
|
||||
import android.widget.TextView
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat
|
||||
import androidx.customview.widget.ExploreByTouchHelper
|
||||
import com.swmansion.enriched.markdown.spans.BaseListSpan
|
||||
import com.swmansion.enriched.markdown.spans.BlockquoteSpan
|
||||
import com.swmansion.enriched.markdown.spans.HeadingSpan
|
||||
import com.swmansion.enriched.markdown.spans.ImageSpan
|
||||
import com.swmansion.enriched.markdown.spans.LinkPillSpan
|
||||
import com.swmansion.enriched.markdown.spans.LinkSpan
|
||||
import com.swmansion.enriched.markdown.spans.OrderedListSpan
|
||||
|
||||
class MarkdownAccessibilityHelper(
|
||||
private val textView: TextView,
|
||||
) : ExploreByTouchHelper(textView) {
|
||||
private var items: List<AccessibilityItem> = emptyList()
|
||||
private var needsRebuild = false
|
||||
private var lastLayoutHashCode = 0
|
||||
private var pendingLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
|
||||
|
||||
var labels: AccessibilityLabels = AccessibilityLabels()
|
||||
set(value) {
|
||||
if (field == value) return
|
||||
field = value
|
||||
invalidateAccessibilityItems()
|
||||
}
|
||||
|
||||
data class AccessibilityItem(
|
||||
val id: Int,
|
||||
val text: String,
|
||||
/** Full character range — used for hit-testing so there are no gaps between items. */
|
||||
val start: Int,
|
||||
val end: Int,
|
||||
/** Trimmed character range — used for bounds calculation to avoid whitespace offsets. */
|
||||
val visibleStart: Int = start,
|
||||
val visibleEnd: Int = end,
|
||||
val headingLevel: Int = 0,
|
||||
val linkUrl: String? = null,
|
||||
val listInfo: ListItemInfo? = null,
|
||||
val imageAltText: String? = null,
|
||||
) {
|
||||
val isHeading get() = headingLevel > 0
|
||||
val isLink get() = linkUrl != null
|
||||
val isListItem get() = listInfo != null
|
||||
val isImage get() = imageAltText != null
|
||||
}
|
||||
|
||||
data class ListItemInfo(
|
||||
val isOrdered: Boolean,
|
||||
val itemNumber: Int,
|
||||
val depth: Int,
|
||||
)
|
||||
|
||||
private data class SpanRange(
|
||||
val start: Int,
|
||||
val end: Int,
|
||||
val headingLevel: Int = 0,
|
||||
val linkUrl: String? = null,
|
||||
val imageAltText: String? = null,
|
||||
)
|
||||
|
||||
fun invalidateAccessibilityItems() {
|
||||
needsRebuild = true
|
||||
if (textView.layout != null) {
|
||||
rebuildIfNeeded()
|
||||
invalidateRoot()
|
||||
} else {
|
||||
schedulePostLayoutRebuild()
|
||||
}
|
||||
}
|
||||
|
||||
private fun schedulePostLayoutRebuild() {
|
||||
if (pendingLayoutListener != null) return
|
||||
val observer = textView.viewTreeObserver
|
||||
if (!observer.isAlive) return
|
||||
val listener =
|
||||
ViewTreeObserver.OnGlobalLayoutListener {
|
||||
removePendingLayoutListener()
|
||||
if (needsRebuild) {
|
||||
rebuildIfNeeded()
|
||||
invalidateRoot()
|
||||
}
|
||||
}
|
||||
pendingLayoutListener = listener
|
||||
observer.addOnGlobalLayoutListener(listener)
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the pending global-layout listener, if any is still registered.
|
||||
*
|
||||
* Must run while the view is attached: `textView.viewTreeObserver` returns
|
||||
* the window's observer only until detach, and the listener was merged into
|
||||
* it from the view's floating observer when the view attached.
|
||||
*/
|
||||
fun cleanup() {
|
||||
removePendingLayoutListener()
|
||||
}
|
||||
|
||||
private fun removePendingLayoutListener() {
|
||||
val listener = pendingLayoutListener ?: return
|
||||
pendingLayoutListener = null
|
||||
val observer = textView.viewTreeObserver
|
||||
if (observer.isAlive) {
|
||||
observer.removeOnGlobalLayoutListener(listener)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* When virtual children exist, prevent the host TextView from appearing as a
|
||||
* standalone focusable element in TalkBack's swipe order. Without this,
|
||||
* `setTextIsSelectable(true)` keeps the view focusable and TalkBack reads
|
||||
* the entire text as one element before entering the virtual hierarchy.
|
||||
*/
|
||||
private fun updateHostFocusability() {
|
||||
val hasVirtualChildren = items.isNotEmpty()
|
||||
ViewCompat.setScreenReaderFocusable(textView, !hasVirtualChildren)
|
||||
textView.importantForAccessibility =
|
||||
if (hasVirtualChildren) View.IMPORTANT_FOR_ACCESSIBILITY_YES else View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
|
||||
}
|
||||
|
||||
private fun rebuildIfNeeded() {
|
||||
val layout = textView.layout ?: return
|
||||
if (needsRebuild || lastLayoutHashCode != layout.hashCode()) {
|
||||
items = buildItems()
|
||||
needsRebuild = false
|
||||
lastLayoutHashCode = layout.hashCode()
|
||||
updateHostFocusability()
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildItems(): List<AccessibilityItem> {
|
||||
val spanned = textView.text as? Spanned ?: return emptyList()
|
||||
if (spanned.isEmpty()) return emptyList()
|
||||
|
||||
val text = spanned.toString()
|
||||
val endLimit = visibleTextLength(text.length)
|
||||
val result = mutableListOf<AccessibilityItem>()
|
||||
var nextId = 0
|
||||
val semanticSpans = collectSemanticSpans(spanned)
|
||||
|
||||
var paraStart = 0
|
||||
while (paraStart < endLimit) {
|
||||
val newlineIdx = text.indexOf('\n', paraStart)
|
||||
val paraEnd = minOf(if (newlineIdx == -1) text.length else newlineIdx + 1, endLimit)
|
||||
val trimmed = text.substring(paraStart, paraEnd).trim()
|
||||
|
||||
if (trimmed.isNotEmpty()) {
|
||||
val spansInParagraph =
|
||||
semanticSpans
|
||||
.filter { it.start < paraEnd && it.end > paraStart }
|
||||
.map { it.copy(end = minOf(it.end, endLimit)) }
|
||||
|
||||
if (spansInParagraph.isEmpty()) {
|
||||
result.add(
|
||||
createTextItem(nextId++, trimmed, paraStart, paraEnd, text, spanned),
|
||||
)
|
||||
} else {
|
||||
nextId = addSegmentedItems(result, spanned, text, paraStart, paraEnd, spansInParagraph, nextId)
|
||||
}
|
||||
}
|
||||
paraStart = paraEnd
|
||||
}
|
||||
|
||||
return result.ifEmpty {
|
||||
val visibleText = text.substring(0, endLimit).trim()
|
||||
if (visibleText.isEmpty()) emptyList() else listOf(AccessibilityItem(0, visibleText, 0, endLimit))
|
||||
}
|
||||
}
|
||||
|
||||
/** Last line that is visible; less than lineCount - 1 when height-capped (e.g. `clip`). */
|
||||
private fun lastVisibleLineIndex(layout: Layout): Int {
|
||||
val maxLines = textView.maxLines.coerceAtLeast(1)
|
||||
return (minOf(layout.lineCount, maxLines) - 1).coerceIn(0, layout.lineCount - 1)
|
||||
}
|
||||
|
||||
/** Ellipsis-aware end offset for a visible line. */
|
||||
private fun visibleLineEnd(
|
||||
layout: Layout,
|
||||
line: Int,
|
||||
): Int {
|
||||
val lineEnd = layout.getLineEnd(line)
|
||||
val count = layout.getEllipsisCount(line)
|
||||
if (count == 0) return lineEnd
|
||||
// Only a tail ellipsis hides text up to the end of the line. Head/middle hide a prefix or an
|
||||
// inner range, so the line end is still laid out and must stay reachable.
|
||||
val hiddenStart = layout.getLineStart(line) + layout.getEllipsisStart(line)
|
||||
return if (hiddenStart + count >= lineEnd) hiddenStart else lineEnd
|
||||
}
|
||||
|
||||
/** End offset of the laid-out (visible) text; less than the full length when truncated. */
|
||||
private fun visibleTextLength(fullLength: Int): Int {
|
||||
val layout = textView.layout ?: return fullLength
|
||||
if (layout.lineCount == 0) return fullLength
|
||||
return minOf(fullLength, maxOf(0, visibleLineEnd(layout, lastVisibleLineIndex(layout))))
|
||||
}
|
||||
|
||||
private fun collectSemanticSpans(spanned: Spanned): List<SpanRange> =
|
||||
(
|
||||
spanned.getSpans(0, spanned.length, HeadingSpan::class.java).map {
|
||||
SpanRange(spanned.getSpanStart(it), spanned.getSpanEnd(it), headingLevel = it.level)
|
||||
} +
|
||||
spanned.getSpans(0, spanned.length, LinkSpan::class.java).map {
|
||||
SpanRange(spanned.getSpanStart(it), spanned.getSpanEnd(it), linkUrl = it.url)
|
||||
} +
|
||||
spanned.getSpans(0, spanned.length, ImageSpan::class.java).map {
|
||||
SpanRange(spanned.getSpanStart(it), spanned.getSpanEnd(it), imageAltText = it.altText)
|
||||
}
|
||||
).sortedBy { it.start }
|
||||
|
||||
private fun addSegmentedItems(
|
||||
items: MutableList<AccessibilityItem>,
|
||||
spanned: Spanned,
|
||||
text: String,
|
||||
paraStart: Int,
|
||||
paraEnd: Int,
|
||||
spans: List<SpanRange>,
|
||||
startId: Int,
|
||||
): Int {
|
||||
var nextId = startId
|
||||
var segmentPos = paraStart
|
||||
|
||||
for (span in spans) {
|
||||
if (span.start < segmentPos) continue
|
||||
|
||||
// Text before the span
|
||||
if (segmentPos < span.start) {
|
||||
val beforeText = text.substring(segmentPos, span.start).trim()
|
||||
if (beforeText.isNotEmpty() && beforeText.any { it.isLetterOrDigit() }) {
|
||||
items.add(createTextItem(nextId++, beforeText, segmentPos, span.start, text, spanned))
|
||||
}
|
||||
}
|
||||
|
||||
// The semantic span itself
|
||||
val pill =
|
||||
if (span.linkUrl != null) {
|
||||
spanned.getSpans(span.start, span.end, LinkPillSpan::class.java).firstOrNull {
|
||||
spanned.getSpanStart(it) == span.start && spanned.getSpanEnd(it) == span.end
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val content = span.imageAltText ?: pill?.accessibilityText ?: spanned.substring(span.start, span.end).trim()
|
||||
if (content.isNotEmpty()) {
|
||||
items.add(createSpanItem(nextId++, content, span, spanned))
|
||||
}
|
||||
segmentPos = span.end
|
||||
}
|
||||
|
||||
// Text after the last span
|
||||
if (segmentPos < paraEnd) {
|
||||
val afterText = text.substring(segmentPos, paraEnd).trim()
|
||||
if (afterText.isNotEmpty() && afterText.any { it.isLetterOrDigit() }) {
|
||||
items.add(createTextItem(nextId++, afterText, segmentPos, paraEnd, text, spanned))
|
||||
}
|
||||
}
|
||||
|
||||
return nextId
|
||||
}
|
||||
|
||||
private fun createTextItem(
|
||||
id: Int,
|
||||
label: String,
|
||||
start: Int,
|
||||
end: Int,
|
||||
text: String,
|
||||
spanned: Spanned,
|
||||
) = AccessibilityItem(
|
||||
id = id,
|
||||
text = label,
|
||||
start = start,
|
||||
end = end,
|
||||
visibleStart = text.findFirstNonWhitespace(start, end),
|
||||
visibleEnd = text.findLastNonWhitespace(start, end),
|
||||
listInfo = getListInfoAt(spanned, start, requireStart = true),
|
||||
)
|
||||
|
||||
private fun createSpanItem(
|
||||
id: Int,
|
||||
content: String,
|
||||
span: SpanRange,
|
||||
spanned: Spanned,
|
||||
): AccessibilityItem {
|
||||
val listContext =
|
||||
if (span.headingLevel > 0 || span.imageAltText != null) {
|
||||
null
|
||||
} else {
|
||||
getListInfoAt(spanned, span.start, requireStart = span.linkUrl == null)
|
||||
}
|
||||
return AccessibilityItem(
|
||||
id = id,
|
||||
text = content,
|
||||
start = span.start,
|
||||
end = span.end,
|
||||
headingLevel = span.headingLevel,
|
||||
linkUrl = span.linkUrl,
|
||||
listInfo = listContext,
|
||||
imageAltText = span.imageAltText,
|
||||
)
|
||||
}
|
||||
|
||||
override fun getVirtualViewAt(
|
||||
x: Float,
|
||||
y: Float,
|
||||
): Int {
|
||||
rebuildIfNeeded()
|
||||
if (items.isEmpty()) return HOST_ID
|
||||
|
||||
val offset = getCharOffsetAt(x, y)
|
||||
|
||||
val exact =
|
||||
items
|
||||
.filter { offset in it.start until it.end }
|
||||
.minByOrNull { it.hitTestPriority }
|
||||
if (exact != null) return exact.id
|
||||
|
||||
return items.minByOrNull { it.distanceTo(offset) }?.id ?: HOST_ID
|
||||
}
|
||||
|
||||
override fun getVisibleVirtualViews(ids: MutableList<Int>) {
|
||||
rebuildIfNeeded()
|
||||
items.forEach { ids.add(it.id) }
|
||||
}
|
||||
|
||||
override fun onPopulateNodeForHost(host: AccessibilityNodeInfoCompat) {
|
||||
super.onPopulateNodeForHost(host)
|
||||
rebuildIfNeeded()
|
||||
if (items.isNotEmpty()) {
|
||||
host.isScreenReaderFocusable = false
|
||||
host.isFocusable = false
|
||||
// Prevent TalkBack from reading the full text when swiping onto the host.
|
||||
// Without this, the host node retains the TextView's text and TalkBack
|
||||
// announces it as a single element before entering the virtual children.
|
||||
host.text = null
|
||||
host.contentDescription = null
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPopulateNodeForVirtualView(
|
||||
id: Int,
|
||||
node: AccessibilityNodeInfoCompat,
|
||||
) {
|
||||
val item = items.getOrNull(id)
|
||||
if (item == null) {
|
||||
node.contentDescription = ""
|
||||
node.setBoundsInParent(Rect())
|
||||
return
|
||||
}
|
||||
node.apply {
|
||||
text = item.text
|
||||
contentDescription = item.text
|
||||
isFocusable = true
|
||||
isScreenReaderFocusable = true
|
||||
setBoundsInParent(boundsForItem(item))
|
||||
applySemantics(item)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPerformActionForVirtualView(
|
||||
id: Int,
|
||||
action: Int,
|
||||
args: Bundle?,
|
||||
): Boolean {
|
||||
val item = items.getOrNull(id) ?: return false
|
||||
if (action == AccessibilityNodeInfoCompat.ACTION_CLICK && item.isLink) {
|
||||
val spanned = textView.text as? Spanned ?: return false
|
||||
val linkSpan = spanned.getSpans(item.start, item.end, LinkSpan::class.java).firstOrNull() ?: return false
|
||||
linkSpan.onClick(textView)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun AccessibilityNodeInfoCompat.applySemantics(item: AccessibilityItem) {
|
||||
item.listInfo?.let { info ->
|
||||
setCollectionItemInfo(
|
||||
AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain(info.itemNumber - 1, 1, 0, 1, false, false),
|
||||
)
|
||||
}
|
||||
|
||||
val blockquoteAnnouncement = blockquoteAnnouncementFor(item)
|
||||
when {
|
||||
item.isHeading -> {
|
||||
isHeading = true
|
||||
if (blockquoteAnnouncement != null) {
|
||||
roleDescription = blockquoteAnnouncement
|
||||
}
|
||||
}
|
||||
|
||||
item.isImage -> {
|
||||
roleDescription = appendBlockquote("image", blockquoteAnnouncement)
|
||||
}
|
||||
|
||||
item.isLink -> {
|
||||
isClickable = true
|
||||
addAction(AccessibilityNodeInfoCompat.AccessibilityActionCompat.ACTION_CLICK)
|
||||
val base = item.listInfo?.let { "link, ${it.listAnnouncement}" } ?: "link"
|
||||
roleDescription = appendBlockquote(base, blockquoteAnnouncement)
|
||||
}
|
||||
|
||||
item.isListItem -> {
|
||||
roleDescription = appendBlockquote(item.listInfo!!.listAnnouncement, blockquoteAnnouncement)
|
||||
}
|
||||
|
||||
blockquoteAnnouncement != null -> {
|
||||
roleDescription = blockquoteAnnouncement
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun appendBlockquote(
|
||||
base: String,
|
||||
blockquoteAnnouncement: String?,
|
||||
): String = if (blockquoteAnnouncement != null) "$base, $blockquoteAnnouncement" else base
|
||||
|
||||
private fun blockquoteAnnouncementFor(item: AccessibilityItem): String? {
|
||||
val spanned = textView.text as? Spanned ?: return null
|
||||
if (spanned.isEmpty()) return null
|
||||
val pos = item.start.coerceIn(0, spanned.length - 1).coerceAtLeast(0)
|
||||
if (pos >= spanned.length) return null
|
||||
val spans = spanned.getSpans(pos, pos + 1, BlockquoteSpan::class.java)
|
||||
if (spans.isEmpty()) return null
|
||||
val maxDepth = spans.maxOf { it.depth }
|
||||
return if (maxDepth >= 1) labels.nestedBlockquote else labels.blockquote
|
||||
}
|
||||
|
||||
private val ListItemInfo.listAnnouncement: String
|
||||
get() {
|
||||
val nested = depth > 0
|
||||
return if (isOrdered) {
|
||||
val template = if (nested) labels.nestedOrderedItem else labels.orderedItem
|
||||
template.replace("{n}", itemNumber.toString())
|
||||
} else {
|
||||
if (nested) labels.nestedBulletPoint else labels.bulletPoint
|
||||
}
|
||||
}
|
||||
|
||||
private fun boundsForItem(item: AccessibilityItem): Rect {
|
||||
val layout = textView.layout ?: return Rect()
|
||||
if (layout.lineCount == 0) return Rect()
|
||||
val maxOffset = visibleLineEnd(layout, lastVisibleLineIndex(layout))
|
||||
val vs = item.visibleStart.coerceIn(0, maxOffset)
|
||||
val ve = item.visibleEnd.coerceIn(vs, maxOffset)
|
||||
|
||||
val startLine = layout.getLineForOffset(vs)
|
||||
val endLine = layout.getLineForOffset(maxOf(vs, ve - 1))
|
||||
|
||||
if (startLine == endLine) {
|
||||
return singleLineBounds(vs, ve, startLine)
|
||||
}
|
||||
|
||||
return multiLineBounds(vs, startLine, endLine)
|
||||
}
|
||||
|
||||
private fun singleLineBounds(
|
||||
start: Int,
|
||||
end: Int,
|
||||
line: Int,
|
||||
): Rect {
|
||||
val layout = textView.layout
|
||||
val left = layout.getPrimaryHorizontal(start).toInt() + textView.paddingLeft
|
||||
val rawRight = layout.getPrimaryHorizontal(end).toInt() + textView.paddingLeft
|
||||
val right = if (rawRight <= left) layout.getLineRight(line).toInt() + textView.paddingLeft else rawRight
|
||||
|
||||
return Rect(
|
||||
left,
|
||||
layout.getLineTop(line) + textView.paddingTop,
|
||||
right,
|
||||
layout.getLineBottom(line) + textView.paddingTop,
|
||||
)
|
||||
}
|
||||
|
||||
private fun multiLineBounds(
|
||||
visibleStart: Int,
|
||||
startLine: Int,
|
||||
endLine: Int,
|
||||
): Rect {
|
||||
val layout = textView.layout
|
||||
val padLeft = textView.paddingLeft
|
||||
|
||||
val firstLineLeft = layout.getPrimaryHorizontal(visibleStart).toInt() + padLeft
|
||||
val firstLineRight = layout.getLineRight(startLine).toInt() + padLeft
|
||||
|
||||
var minLeft = firstLineLeft
|
||||
var maxRight = firstLineRight
|
||||
for (line in (startLine + 1)..endLine) {
|
||||
minLeft = minOf(minLeft, layout.getLineLeft(line).toInt() + padLeft)
|
||||
maxRight = maxOf(maxRight, layout.getLineRight(line).toInt() + padLeft)
|
||||
}
|
||||
|
||||
return Rect(
|
||||
minOf(firstLineLeft, minLeft),
|
||||
layout.getLineTop(startLine) + textView.paddingTop,
|
||||
maxRight,
|
||||
layout.getLineBottom(endLine) + textView.paddingTop,
|
||||
)
|
||||
}
|
||||
|
||||
private fun getCharOffsetAt(
|
||||
x: Float,
|
||||
y: Float,
|
||||
): Int {
|
||||
val layout = textView.layout ?: return 0
|
||||
val line = layout.getLineForVertical(y.toInt()).coerceIn(0, layout.lineCount - 1)
|
||||
return layout.getOffsetForHorizontal(line, x)
|
||||
}
|
||||
|
||||
private val AccessibilityItem.hitTestPriority: Int
|
||||
get() =
|
||||
when {
|
||||
isLink -> 0
|
||||
isImage -> 1
|
||||
isHeading -> 2
|
||||
isListItem -> 3
|
||||
else -> 4
|
||||
}
|
||||
|
||||
private fun AccessibilityItem.distanceTo(offset: Int): Int =
|
||||
when {
|
||||
offset < start -> start - offset
|
||||
offset >= end -> offset - end + 1
|
||||
else -> 0
|
||||
}
|
||||
|
||||
private fun getListInfoAt(
|
||||
spanned: Spanned,
|
||||
position: Int,
|
||||
requireStart: Boolean,
|
||||
): ListItemInfo? {
|
||||
val deepest =
|
||||
spanned
|
||||
.getSpans(position, position + 1, BaseListSpan::class.java)
|
||||
.maxByOrNull { it.depth } ?: return null
|
||||
|
||||
if (requireStart) {
|
||||
val spanStart = spanned.getSpanStart(deepest)
|
||||
val firstChar =
|
||||
(spanStart until minOf(spanStart + 10, spanned.length))
|
||||
.firstOrNull { !spanned[it].isWhitespace() } ?: spanStart
|
||||
if (position > firstChar + 1) return null
|
||||
}
|
||||
|
||||
return ListItemInfo(
|
||||
isOrdered = deepest is OrderedListSpan,
|
||||
itemNumber = (deepest as? OrderedListSpan)?.itemNumber ?: 0,
|
||||
depth = deepest.depth,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun String.findFirstNonWhitespace(
|
||||
from: Int,
|
||||
to: Int,
|
||||
): Int {
|
||||
for (i in from until to) {
|
||||
if (!this[i].isWhitespace()) return i
|
||||
}
|
||||
return from
|
||||
}
|
||||
|
||||
private fun String.findLastNonWhitespace(
|
||||
from: Int,
|
||||
to: Int,
|
||||
): Int {
|
||||
for (i in (to - 1) downTo from) {
|
||||
if (!this[i].isWhitespace()) return i + 1
|
||||
}
|
||||
return to
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.swmansion.enriched.markdown.events
|
||||
|
||||
import com.facebook.react.bridge.Arguments
|
||||
import com.facebook.react.bridge.WritableMap
|
||||
import com.facebook.react.uimanager.events.Event
|
||||
|
||||
class CodeBlockPressEvent(
|
||||
surfaceId: Int,
|
||||
viewId: Int,
|
||||
private val code: String,
|
||||
private val language: String,
|
||||
) : Event<CodeBlockPressEvent>(surfaceId, viewId) {
|
||||
override fun getEventName(): String = EVENT_NAME
|
||||
|
||||
override fun getEventData(): WritableMap =
|
||||
Arguments.createMap().apply {
|
||||
putString("code", code)
|
||||
putString("language", language)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EVENT_NAME: String = "onCodeBlockPress"
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.swmansion.enriched.markdown.events
|
||||
|
||||
import com.facebook.react.bridge.Arguments
|
||||
import com.facebook.react.bridge.WritableMap
|
||||
import com.facebook.react.uimanager.events.Event
|
||||
|
||||
class ContextMenuItemPressEvent(
|
||||
surfaceId: Int,
|
||||
viewId: Int,
|
||||
private val itemText: String,
|
||||
private val selectedText: String,
|
||||
private val selectionStart: Int,
|
||||
private val selectionEnd: Int,
|
||||
) : Event<ContextMenuItemPressEvent>(surfaceId, viewId) {
|
||||
override fun getEventName(): String = EVENT_NAME
|
||||
|
||||
override fun getEventData(): WritableMap =
|
||||
Arguments.createMap().apply {
|
||||
putString("itemText", itemText)
|
||||
putString("selectedText", selectedText)
|
||||
putInt("selectionStart", selectionStart)
|
||||
putInt("selectionEnd", selectionEnd)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EVENT_NAME = "onContextMenuItemPress"
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.swmansion.enriched.markdown.events
|
||||
|
||||
import com.facebook.react.bridge.Arguments
|
||||
import com.facebook.react.bridge.WritableMap
|
||||
import com.facebook.react.uimanager.events.Event
|
||||
|
||||
class CopyPressEvent(
|
||||
surfaceId: Int,
|
||||
viewId: Int,
|
||||
private val code: String,
|
||||
private val language: String,
|
||||
) : Event<CopyPressEvent>(surfaceId, viewId) {
|
||||
override fun getEventName(): String = EVENT_NAME
|
||||
|
||||
override fun getEventData(): WritableMap =
|
||||
Arguments.createMap().apply {
|
||||
putString("code", code)
|
||||
putString("language", language)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EVENT_NAME: String = "onCopyPress"
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.swmansion.enriched.markdown.events
|
||||
|
||||
import com.facebook.react.bridge.Arguments
|
||||
import com.facebook.react.bridge.WritableMap
|
||||
import com.facebook.react.uimanager.events.Event
|
||||
|
||||
class ImagePressEvent(
|
||||
surfaceId: Int,
|
||||
viewId: Int,
|
||||
private val url: String,
|
||||
private val altText: String,
|
||||
) : Event<ImagePressEvent>(surfaceId, viewId) {
|
||||
override fun getEventName(): String = EVENT_NAME
|
||||
|
||||
override fun getEventData(): WritableMap {
|
||||
val eventData: WritableMap = Arguments.createMap()
|
||||
eventData.putString("url", url)
|
||||
eventData.putString("altText", altText)
|
||||
return eventData
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EVENT_NAME: String = "onImagePress"
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.swmansion.enriched.markdown.events
|
||||
|
||||
import com.facebook.react.bridge.Arguments
|
||||
import com.facebook.react.bridge.WritableMap
|
||||
import com.facebook.react.uimanager.events.Event
|
||||
|
||||
class LatexErrorEvent(
|
||||
surfaceId: Int,
|
||||
viewId: Int,
|
||||
private val source: String,
|
||||
private val message: String?,
|
||||
private val displayMode: Boolean,
|
||||
) : Event<LatexErrorEvent>(surfaceId, viewId) {
|
||||
override fun getEventName(): String = EVENT_NAME
|
||||
|
||||
override fun canCoalesce(): Boolean = false
|
||||
|
||||
override fun getEventData(): WritableMap {
|
||||
val eventData: WritableMap = Arguments.createMap()
|
||||
eventData.putString("source", source)
|
||||
eventData.putString("message", message)
|
||||
eventData.putBoolean("displayMode", displayMode)
|
||||
return eventData
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EVENT_NAME: String = "onLatexError"
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.swmansion.enriched.markdown.events
|
||||
|
||||
import com.facebook.react.bridge.Arguments
|
||||
import com.facebook.react.bridge.WritableMap
|
||||
import com.facebook.react.uimanager.events.Event
|
||||
|
||||
class LinkLongPressEvent(
|
||||
surfaceId: Int,
|
||||
viewId: Int,
|
||||
private val url: String,
|
||||
) : Event<LinkLongPressEvent>(surfaceId, viewId) {
|
||||
override fun getEventName(): String = EVENT_NAME
|
||||
|
||||
override fun getEventData(): WritableMap {
|
||||
val eventData: WritableMap = Arguments.createMap()
|
||||
eventData.putString("url", url)
|
||||
return eventData
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EVENT_NAME: String = "onLinkLongPress"
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.swmansion.enriched.markdown.events
|
||||
|
||||
import com.facebook.react.bridge.Arguments
|
||||
import com.facebook.react.bridge.WritableMap
|
||||
import com.facebook.react.uimanager.events.Event
|
||||
|
||||
class LinkPressEvent(
|
||||
surfaceId: Int,
|
||||
viewId: Int,
|
||||
private val url: String,
|
||||
private val sourceType: String,
|
||||
) : Event<LinkPressEvent>(surfaceId, viewId) {
|
||||
override fun getEventName(): String = EVENT_NAME
|
||||
|
||||
override fun getEventData(): WritableMap {
|
||||
val eventData: WritableMap = Arguments.createMap()
|
||||
eventData.putString("url", url)
|
||||
eventData.putString("sourceType", sourceType)
|
||||
return eventData
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EVENT_NAME: String = "onLinkPress"
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.swmansion.enriched.markdown.events
|
||||
|
||||
import com.facebook.react.bridge.Arguments
|
||||
import com.facebook.react.bridge.WritableMap
|
||||
import com.facebook.react.uimanager.events.Event
|
||||
|
||||
class TaskListItemPressEvent(
|
||||
surfaceId: Int,
|
||||
viewId: Int,
|
||||
private val taskIndex: Int,
|
||||
private val checked: Boolean,
|
||||
private val itemText: String,
|
||||
) : Event<TaskListItemPressEvent>(surfaceId, viewId) {
|
||||
override fun getEventName(): String = EVENT_NAME
|
||||
|
||||
override fun getEventData(): WritableMap =
|
||||
Arguments.createMap().apply {
|
||||
putInt("index", taskIndex)
|
||||
putBoolean("checked", checked)
|
||||
putString("text", itemText)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EVENT_NAME: String = "onTaskListItemPress"
|
||||
}
|
||||
}
|
||||
+536
@@ -0,0 +1,536 @@
|
||||
package com.swmansion.enriched.markdown.input
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
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.EnrichedMarkdownTextInputManagerDelegate
|
||||
import com.facebook.react.viewmanagers.EnrichedMarkdownTextInputManagerInterface
|
||||
import com.facebook.yoga.YogaMeasureMode
|
||||
import com.swmansion.enriched.markdown.input.editing.MarkdownShortcutsConfig
|
||||
import com.swmansion.enriched.markdown.input.events.OnCaretRectChangeEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnChangeMarkdownEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnChangeMentionEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnChangeSelectionEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnChangeStateEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnChangeTextEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnContextMenuItemPressEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnEndMentionEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnInputBlurEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnInputFocusEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnInputKeyPressEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnLinkDetectedEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnRequestCaretRectResultEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnRequestMarkdownResultEvent
|
||||
import com.swmansion.enriched.markdown.input.events.OnStartMentionEvent
|
||||
import com.swmansion.enriched.markdown.input.layout.InputMeasurementStore
|
||||
import com.swmansion.enriched.markdown.input.model.StyleType
|
||||
import com.swmansion.enriched.markdown.input.toolbar.FormatMenuConfig
|
||||
import com.swmansion.enriched.markdown.input.toolbar.InputSelectionMenuConfig
|
||||
import com.swmansion.enriched.markdown.utils.common.LinkRegexConfig
|
||||
import com.swmansion.enriched.markdown.utils.input.BorderPropsApplicator
|
||||
import com.swmansion.enriched.markdown.utils.input.MarkdownStyleParser
|
||||
|
||||
@ReactModule(name = EnrichedMarkdownTextInputManager.NAME)
|
||||
class EnrichedMarkdownTextInputManager :
|
||||
SimpleViewManager<EnrichedMarkdownTextInputView>(),
|
||||
EnrichedMarkdownTextInputManagerInterface<EnrichedMarkdownTextInputView> {
|
||||
private val delegate: ViewManagerDelegate<EnrichedMarkdownTextInputView> =
|
||||
EnrichedMarkdownTextInputManagerDelegate(this)
|
||||
|
||||
override fun getDelegate(): ViewManagerDelegate<EnrichedMarkdownTextInputView> = delegate
|
||||
|
||||
override fun getName(): String = NAME
|
||||
|
||||
override fun createViewInstance(reactContext: ThemedReactContext): EnrichedMarkdownTextInputView =
|
||||
EnrichedMarkdownTextInputView(reactContext)
|
||||
|
||||
override fun updateState(
|
||||
view: EnrichedMarkdownTextInputView,
|
||||
props: ReactStylesDiffMap?,
|
||||
stateWrapper: StateWrapper?,
|
||||
): Any? {
|
||||
view.stateWrapper = stateWrapper
|
||||
return super.updateState(view, props, stateWrapper)
|
||||
}
|
||||
|
||||
override fun onAfterUpdateTransaction(view: EnrichedMarkdownTextInputView) {
|
||||
super.onAfterUpdateTransaction(view)
|
||||
view.afterUpdateTransaction()
|
||||
}
|
||||
|
||||
override fun onDropViewInstance(view: EnrichedMarkdownTextInputView) {
|
||||
view.dismissActiveMention()
|
||||
super.onDropViewInstance(view)
|
||||
view.layoutManager.release()
|
||||
}
|
||||
|
||||
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 InputMeasurementStore.getMeasureById(context, id, width, height, heightMode, props)
|
||||
}
|
||||
|
||||
override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> =
|
||||
listOf(
|
||||
OnChangeTextEvent.EVENT_NAME,
|
||||
OnChangeMarkdownEvent.EVENT_NAME,
|
||||
OnChangeSelectionEvent.EVENT_NAME,
|
||||
OnChangeStateEvent.EVENT_NAME,
|
||||
OnInputKeyPressEvent.EVENT_NAME,
|
||||
OnRequestMarkdownResultEvent.EVENT_NAME,
|
||||
OnRequestCaretRectResultEvent.EVENT_NAME,
|
||||
OnCaretRectChangeEvent.EVENT_NAME,
|
||||
OnInputFocusEvent.EVENT_NAME,
|
||||
OnInputBlurEvent.EVENT_NAME,
|
||||
OnContextMenuItemPressEvent.EVENT_NAME,
|
||||
OnLinkDetectedEvent.EVENT_NAME,
|
||||
OnStartMentionEvent.EVENT_NAME,
|
||||
OnChangeMentionEvent.EVENT_NAME,
|
||||
OnEndMentionEvent.EVENT_NAME,
|
||||
).associateWithTo(mutableMapOf()) { name -> mapOf("registrationName" to name) }
|
||||
|
||||
// Props
|
||||
|
||||
@ReactProp(name = "defaultValue")
|
||||
override fun setDefaultValue(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: String?,
|
||||
) {
|
||||
if (value != null && view?.text?.isEmpty() == true) {
|
||||
view.setValueFromJS(value)
|
||||
}
|
||||
}
|
||||
|
||||
@ReactProp(name = "placeholder")
|
||||
override fun setPlaceholder(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: String?,
|
||||
) {
|
||||
view?.setUserHint(value)
|
||||
}
|
||||
|
||||
@ReactProp(name = "placeholderTextColor", customType = "Color")
|
||||
override fun setPlaceholderTextColor(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: Int?,
|
||||
) {
|
||||
view?.setHintTextColor(value ?: Color.GRAY)
|
||||
}
|
||||
|
||||
@ReactProp(name = "editable", defaultBoolean = true)
|
||||
override fun setEditable(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: Boolean,
|
||||
) {
|
||||
view?.isEnabled = value
|
||||
}
|
||||
|
||||
@ReactProp(name = "autoFocus", defaultBoolean = false)
|
||||
override fun setAutoFocus(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: Boolean,
|
||||
) {
|
||||
view?.autoFocusRequested = value
|
||||
}
|
||||
|
||||
@ReactProp(name = "scrollEnabled", defaultBoolean = true)
|
||||
override fun setScrollEnabled(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: Boolean,
|
||||
) {
|
||||
view?.scrollEnabled = value
|
||||
view?.isVerticalScrollBarEnabled = value
|
||||
}
|
||||
|
||||
@ReactProp(name = "markdownShortcuts")
|
||||
override fun setMarkdownShortcuts(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: ReadableMap?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.markdownShortcuts =
|
||||
if (value == null) {
|
||||
MarkdownShortcutsConfig()
|
||||
} else {
|
||||
MarkdownShortcutsConfig(
|
||||
heading = value.getBoolean("heading"),
|
||||
unorderedList = value.getBoolean("unorderedList"),
|
||||
orderedList = value.getBoolean("orderedList"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ReactProp(name = "autoCapitalize")
|
||||
override fun setAutoCapitalize(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: String?,
|
||||
) {
|
||||
view?.setAutoCapitalize(value)
|
||||
}
|
||||
|
||||
@ReactProp(name = "multiline", defaultBoolean = true)
|
||||
override fun setMultiline(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: Boolean,
|
||||
) {
|
||||
view?.isSingleLine = !value
|
||||
}
|
||||
|
||||
@ReactProp(name = "cursorColor", customType = "Color")
|
||||
override fun setCursorColor(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: Int?,
|
||||
) {
|
||||
view?.setCursorColorFromProps(value)
|
||||
}
|
||||
|
||||
@ReactProp(name = "selectionColor", customType = "Color")
|
||||
override fun setSelectionColor(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: Int?,
|
||||
) {
|
||||
if (value != null) {
|
||||
view?.highlightColor = value
|
||||
}
|
||||
}
|
||||
|
||||
@ReactProp(name = "markdownStyle")
|
||||
override fun setMarkdownStyle(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: ReadableMap?,
|
||||
) {
|
||||
if (view == null || value == null) return
|
||||
|
||||
view.setMarkdownStyleFromProps(MarkdownStyleParser.parse(value))
|
||||
// This call takes care of setting formattingDirty if needed, so we don't
|
||||
// need to explicitly apply formatting or set it here separately
|
||||
}
|
||||
|
||||
@ReactProp(name = "color", customType = "Color")
|
||||
override fun setColor(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: Int?,
|
||||
) {
|
||||
view?.setColorFromProps(value)
|
||||
}
|
||||
|
||||
@ReactProp(name = "fontSize", defaultFloat = 16f)
|
||||
override fun setFontSize(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: Float,
|
||||
) {
|
||||
view?.setFontSizeFromProps(value)
|
||||
}
|
||||
|
||||
@ReactProp(name = "lineHeight", defaultFloat = 0f)
|
||||
override fun setLineHeight(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: Float,
|
||||
) {
|
||||
view?.setLineHeightFromProps(value)
|
||||
}
|
||||
|
||||
@ReactProp(name = "fontFamily")
|
||||
override fun setFontFamily(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: String?,
|
||||
) {
|
||||
view?.setFontFamily(value)
|
||||
}
|
||||
|
||||
@ReactProp(name = "fontWeight")
|
||||
override fun setFontWeight(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: String?,
|
||||
) {
|
||||
view?.setFontWeight(value)
|
||||
}
|
||||
|
||||
@ReactProp(name = "isOnChangeMarkdownSet", defaultBoolean = false)
|
||||
override fun setIsOnChangeMarkdownSet(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: Boolean,
|
||||
) {
|
||||
view?.emitMarkdown = value
|
||||
}
|
||||
|
||||
@ReactProp(name = "contextMenuItems")
|
||||
override fun setContextMenuItems(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: ReadableArray?,
|
||||
) {
|
||||
if (view == null) return
|
||||
val items = (0 until (value?.size() ?: 0)).mapNotNull { value?.getMap(it)?.getString("text") }
|
||||
view.setContextMenuItems(items)
|
||||
}
|
||||
|
||||
@ReactProp(name = "selectionMenuConfig")
|
||||
override fun setSelectionMenuConfig(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: ReadableMap?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.contextMenu.selectionMenuConfig =
|
||||
if (value == null) {
|
||||
InputSelectionMenuConfig()
|
||||
} else {
|
||||
InputSelectionMenuConfig(
|
||||
format = value.getBoolean("format"),
|
||||
formatLabel = value.getString("formatLabel") ?: "",
|
||||
copyAsMarkdown = value.getBoolean("copyAsMarkdown"),
|
||||
copyAsMarkdownLabel = value.getString("copyAsMarkdownLabel") ?: "",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ReactProp(name = "formatMenuConfig")
|
||||
override fun setFormatMenuConfig(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: ReadableMap?,
|
||||
) {
|
||||
if (view == null) return
|
||||
view.contextMenu.formatMenuConfig =
|
||||
if (value == null) {
|
||||
FormatMenuConfig()
|
||||
} else {
|
||||
FormatMenuConfig(
|
||||
bold = value.getBoolean("bold"),
|
||||
boldLabel = value.getString("boldLabel") ?: "",
|
||||
italic = value.getBoolean("italic"),
|
||||
italicLabel = value.getString("italicLabel") ?: "",
|
||||
underline = value.getBoolean("underline"),
|
||||
underlineLabel = value.getString("underlineLabel") ?: "",
|
||||
strikethrough = value.getBoolean("strikethrough"),
|
||||
strikethroughLabel = value.getString("strikethroughLabel") ?: "",
|
||||
spoiler = value.getBoolean("spoiler"),
|
||||
spoilerLabel = value.getString("spoilerLabel") ?: "",
|
||||
link = value.getBoolean("link"),
|
||||
linkLabel = value.getString("linkLabel") ?: "",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ReactProp(name = "linkRegex")
|
||||
override fun setLinkRegex(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: ReadableMap?,
|
||||
) {
|
||||
if (view == null) return
|
||||
val config =
|
||||
if (value != null) {
|
||||
LinkRegexConfig(
|
||||
pattern = value.getString("pattern") ?: "",
|
||||
caseInsensitive = value.getBoolean("caseInsensitive"),
|
||||
dotAll = value.getBoolean("dotAll"),
|
||||
isDisabled = value.getBoolean("isDisabled"),
|
||||
isDefault = value.getBoolean("isDefault"),
|
||||
)
|
||||
} else {
|
||||
LinkRegexConfig("", caseInsensitive = false, dotAll = false, isDisabled = false, isDefault = true)
|
||||
}
|
||||
view.setLinkRegex(config)
|
||||
}
|
||||
|
||||
@ReactProp(name = "mentionIndicators")
|
||||
override fun setMentionIndicators(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: ReadableArray?,
|
||||
) {
|
||||
val indicators =
|
||||
(0 until (value?.size() ?: 0))
|
||||
.mapNotNull { value?.getString(it) }
|
||||
.filter { it.isNotEmpty() }
|
||||
view?.setMentionIndicators(indicators)
|
||||
}
|
||||
|
||||
@ReactProp(name = "writingDirection")
|
||||
override fun setWritingDirection(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
value: String?,
|
||||
) {
|
||||
// No-op on Android — EditText resolves direction per paragraph via
|
||||
// TEXT_DIRECTION_FIRST_STRONG (the platform default).
|
||||
}
|
||||
|
||||
override fun updateProperties(
|
||||
view: EnrichedMarkdownTextInputView,
|
||||
props: ReactStylesDiffMap,
|
||||
) {
|
||||
BorderPropsApplicator.apply(view, props)
|
||||
super.updateProperties(view, props)
|
||||
}
|
||||
|
||||
override fun setPadding(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
left: Int,
|
||||
top: Int,
|
||||
right: Int,
|
||||
bottom: Int,
|
||||
) {
|
||||
super.setPadding(view, left, top, right, bottom)
|
||||
view?.setPadding(left, top, right, bottom)
|
||||
}
|
||||
|
||||
// Commands
|
||||
|
||||
override fun focus(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.requestFocusProgrammatically()
|
||||
}
|
||||
|
||||
override fun blur(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.clearFocus()
|
||||
}
|
||||
|
||||
override fun setValue(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
markdown: String?,
|
||||
) {
|
||||
if (markdown != null) {
|
||||
view?.setValueFromJS(markdown)
|
||||
}
|
||||
}
|
||||
|
||||
override fun setSelection(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
start: Int,
|
||||
end: Int,
|
||||
) {
|
||||
val length = view?.text?.length ?: 0
|
||||
val clampedStart = start.coerceIn(0, length)
|
||||
val clampedEnd = end.coerceIn(0, length)
|
||||
view?.setSelection(clampedStart, clampedEnd)
|
||||
}
|
||||
|
||||
override fun toggleBold(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.toggleInlineStyle(StyleType.BOLD)
|
||||
}
|
||||
|
||||
override fun toggleItalic(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.toggleInlineStyle(StyleType.ITALIC)
|
||||
}
|
||||
|
||||
override fun toggleUnderline(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.toggleInlineStyle(StyleType.UNDERLINE)
|
||||
}
|
||||
|
||||
override fun toggleStrikethrough(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.toggleInlineStyle(StyleType.STRIKETHROUGH)
|
||||
}
|
||||
|
||||
override fun toggleSpoiler(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.toggleInlineStyle(StyleType.SPOILER)
|
||||
}
|
||||
|
||||
override fun toggleHeading(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
level: Int,
|
||||
) {
|
||||
view?.toggleHeading(level)
|
||||
}
|
||||
|
||||
override fun toggleUnorderedList(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.toggleUnorderedList()
|
||||
}
|
||||
|
||||
override fun toggleOrderedList(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.toggleOrderedList()
|
||||
}
|
||||
|
||||
override fun indentList(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.indentList()
|
||||
}
|
||||
|
||||
override fun outdentList(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.outdentList()
|
||||
}
|
||||
|
||||
override fun setLink(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
url: String?,
|
||||
) {
|
||||
if (url != null) {
|
||||
view?.setLinkForSelection(url)
|
||||
}
|
||||
}
|
||||
|
||||
override fun insertLink(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
text: String?,
|
||||
url: String?,
|
||||
) {
|
||||
if (url != null) {
|
||||
view?.insertLinkAtCursor(text ?: url, url)
|
||||
}
|
||||
}
|
||||
|
||||
override fun insertText(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
text: String?,
|
||||
) {
|
||||
if (text != null) {
|
||||
view?.insertTextAtCursor(text)
|
||||
}
|
||||
}
|
||||
|
||||
override fun insertMention(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
displayText: String?,
|
||||
url: String?,
|
||||
) {
|
||||
if (displayText != null && url != null) {
|
||||
view?.insertMention(displayText, url)
|
||||
}
|
||||
}
|
||||
|
||||
override fun startMention(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
indicator: String?,
|
||||
) {
|
||||
if (indicator != null) {
|
||||
view?.startMention(indicator)
|
||||
}
|
||||
}
|
||||
|
||||
override fun removeLink(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.removeLinkAtCursor()
|
||||
}
|
||||
|
||||
override fun copyToClipboard(view: EnrichedMarkdownTextInputView?) {
|
||||
view?.copyToClipboard()
|
||||
}
|
||||
|
||||
override fun requestMarkdown(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
requestId: Int,
|
||||
) {
|
||||
view?.eventEmitter?.emitRequestMarkdownResult(requestId)
|
||||
}
|
||||
|
||||
override fun requestCaretRect(
|
||||
view: EnrichedMarkdownTextInputView?,
|
||||
requestId: Int,
|
||||
) {
|
||||
view?.eventEmitter?.emitRequestCaretRectResult(requestId)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val NAME = "EnrichedMarkdownTextInput"
|
||||
}
|
||||
}
|
||||
+1248
File diff suppressed because it is too large
Load Diff
+42
@@ -0,0 +1,42 @@
|
||||
package com.swmansion.enriched.markdown.input
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipDescription
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.os.PersistableBundle
|
||||
|
||||
/**
|
||||
* Clipboard round-trip for markdown content, mirroring iOS's dual pasteboard
|
||||
* representation: the clip's item text stays clean plain text for external
|
||||
* paste targets, while the markdown source travels in the description extras
|
||||
* under a vendor MIME type so our paste can restore formatting and block
|
||||
* ranges. External clips (no vendor MIME) keep pasting as plain text.
|
||||
*/
|
||||
object MarkdownClipboard {
|
||||
const val MIME_TYPE = "text/vnd.com.swmansion.enriched-markdown"
|
||||
private const val EXTRA_MARKDOWN = "com.swmansion.enriched-markdown.markdown"
|
||||
|
||||
fun newMarkdownClip(
|
||||
markdown: String,
|
||||
plainText: String,
|
||||
): ClipData {
|
||||
val clip =
|
||||
ClipData(
|
||||
ClipDescription("Markdown", arrayOf(MIME_TYPE, ClipDescription.MIMETYPE_TEXT_PLAIN)),
|
||||
ClipData.Item(plainText),
|
||||
)
|
||||
clip.description.extras = PersistableBundle().apply { putString(EXTRA_MARKDOWN, markdown) }
|
||||
return clip
|
||||
}
|
||||
|
||||
/** Returns the clipboard's markdown, or null if the clip wasn't created by [newMarkdownClip]. */
|
||||
fun markdownFromClipboard(context: Context): String? {
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager ?: return null
|
||||
val clip = clipboard.primaryClip ?: return null
|
||||
if (!clip.description.hasMimeType(MIME_TYPE)) return null
|
||||
return clip.description.extras
|
||||
?.getString(EXTRA_MARKDOWN)
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.swmansion.enriched.markdown.input.autolink
|
||||
|
||||
import android.text.TextPaint
|
||||
import android.text.style.CharacterStyle
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.UnderlineSpan
|
||||
|
||||
/**
|
||||
* Visual spans for auto-detected links. These intentionally do NOT implement
|
||||
* MarkdownSpan so they survive the diff-based removal in InputFormatter.applyFormatting.
|
||||
*/
|
||||
class AutoDetectedLinkColorSpan(
|
||||
color: Int,
|
||||
) : ForegroundColorSpan(color)
|
||||
|
||||
class AutoDetectedLinkUnderlineSpan : UnderlineSpan()
|
||||
|
||||
/**
|
||||
* Zero-width marker span that carries the matched URL and marks a range as
|
||||
* auto-detected. Used to enumerate existing auto-link ranges without confusing
|
||||
* them with manual MarkdownSpan link spans.
|
||||
*/
|
||||
class AutoDetectedLinkMarkerSpan(
|
||||
val url: String,
|
||||
) : CharacterStyle() {
|
||||
override fun updateDrawState(tp: TextPaint) {
|
||||
// no-op — styling is handled by the color/underline spans
|
||||
}
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
package com.swmansion.enriched.markdown.input.autolink
|
||||
|
||||
import android.text.Spannable
|
||||
import com.swmansion.enriched.markdown.input.detection.TextDetector
|
||||
import com.swmansion.enriched.markdown.input.detection.WordResult
|
||||
import com.swmansion.enriched.markdown.input.formatting.FormattingStore
|
||||
import com.swmansion.enriched.markdown.input.model.FormattingRange
|
||||
import com.swmansion.enriched.markdown.input.model.InputFormatterStyle
|
||||
import com.swmansion.enriched.markdown.input.model.StyleType
|
||||
import com.swmansion.enriched.markdown.utils.common.LinkRegexConfig
|
||||
import java.util.regex.Pattern
|
||||
|
||||
typealias OnLinkDetectedCallback = (text: String, url: String, start: Int, end: Int) -> Unit
|
||||
|
||||
class AutoLinkDetector(
|
||||
private val formattingStore: FormattingStore,
|
||||
) : TextDetector {
|
||||
private var config: LinkRegexConfig? = null
|
||||
private var compiledPattern: Pattern? = null
|
||||
var style: InputFormatterStyle? = null
|
||||
var onLinkDetected: OnLinkDetectedCallback? = null
|
||||
|
||||
fun setRegexConfig(newConfig: LinkRegexConfig) {
|
||||
if (newConfig == config) return
|
||||
config = newConfig
|
||||
compiledPattern = null
|
||||
|
||||
if (!newConfig.isDefault && !newConfig.isDisabled && newConfig.pattern.isNotEmpty()) {
|
||||
var flags = 0
|
||||
if (newConfig.caseInsensitive) flags = flags or Pattern.CASE_INSENSITIVE
|
||||
if (newConfig.dotAll) flags = flags or Pattern.DOTALL
|
||||
compiledPattern =
|
||||
try {
|
||||
Pattern.compile(newConfig.pattern, flags)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun processWord(
|
||||
spannable: Spannable,
|
||||
wordResult: WordResult,
|
||||
) {
|
||||
val detectedUrl = detectNewLinkInWord(spannable, wordResult)
|
||||
if (detectedUrl != null) {
|
||||
onLinkDetected?.invoke(wordResult.word, detectedUrl, wordResult.start, wordResult.end)
|
||||
}
|
||||
}
|
||||
|
||||
override fun refreshStyling(spannable: Spannable) {
|
||||
val currentStyle = style ?: return
|
||||
val markers = spannable.getSpans(0, spannable.length, AutoDetectedLinkMarkerSpan::class.java)
|
||||
for (marker in markers) {
|
||||
val start = spannable.getSpanStart(marker)
|
||||
val end = spannable.getSpanEnd(marker)
|
||||
applyVisualStyling(spannable, start, end, currentStyle)
|
||||
}
|
||||
}
|
||||
|
||||
override fun transientFormattingRanges(spannable: Spannable): List<FormattingRange> {
|
||||
val markers = spannable.getSpans(0, spannable.length, AutoDetectedLinkMarkerSpan::class.java)
|
||||
return markers.map { marker ->
|
||||
FormattingRange(
|
||||
StyleType.LINK,
|
||||
spannable.getSpanStart(marker),
|
||||
spannable.getSpanEnd(marker),
|
||||
marker.url,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun clearAutoLinkInRange(
|
||||
spannable: Spannable,
|
||||
start: Int,
|
||||
end: Int,
|
||||
) {
|
||||
removeAutoLinkSpans(spannable, start, end)
|
||||
}
|
||||
|
||||
private fun detectNewLinkInWord(
|
||||
spannable: Spannable,
|
||||
wordResult: WordResult,
|
||||
): String? {
|
||||
if (config?.isDisabled == true) return null
|
||||
|
||||
val (word, wordStart, wordEnd) = wordResult
|
||||
|
||||
val hasManualLink = formattingStore.rangeOfType(StyleType.LINK, wordStart) != null
|
||||
if (hasManualLink) {
|
||||
removeAutoLinkSpans(spannable, wordStart, wordEnd)
|
||||
return null
|
||||
}
|
||||
|
||||
val matchedUrl = matchWord(word)
|
||||
val existingMarker =
|
||||
spannable
|
||||
.getSpans(wordStart, wordEnd, AutoDetectedLinkMarkerSpan::class.java)
|
||||
.firstOrNull { spannable.getSpanStart(it) == wordStart && spannable.getSpanEnd(it) == wordEnd }
|
||||
|
||||
if (matchedUrl != null) {
|
||||
if (existingMarker?.url == matchedUrl) return null
|
||||
|
||||
removeAutoLinkSpans(spannable, wordStart, wordEnd)
|
||||
spannable.setSpan(
|
||||
AutoDetectedLinkMarkerSpan(matchedUrl),
|
||||
wordStart,
|
||||
wordEnd,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
|
||||
)
|
||||
val currentStyle = style
|
||||
if (currentStyle != null) {
|
||||
applyVisualStyling(spannable, wordStart, wordEnd, currentStyle)
|
||||
}
|
||||
return matchedUrl
|
||||
} else {
|
||||
if (existingMarker != null) {
|
||||
removeAutoLinkSpans(spannable, wordStart, wordEnd)
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private fun matchWord(word: String): String? {
|
||||
if (word.isEmpty()) return null
|
||||
|
||||
val custom = compiledPattern
|
||||
if (custom != null) {
|
||||
return if (custom.matcher(word).matches()) normalizeUrl(word) else null
|
||||
}
|
||||
|
||||
if (DEFAULT_PATTERN.matcher(word).matches()) return normalizeUrl(word)
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
private fun removeAutoLinkSpans(
|
||||
spannable: Spannable,
|
||||
start: Int,
|
||||
end: Int,
|
||||
) {
|
||||
for (span in spannable.getSpans(start, end, AutoDetectedLinkMarkerSpan::class.java)) {
|
||||
spannable.removeSpan(span)
|
||||
}
|
||||
for (span in spannable.getSpans(start, end, AutoDetectedLinkColorSpan::class.java)) {
|
||||
spannable.removeSpan(span)
|
||||
}
|
||||
for (span in spannable.getSpans(start, end, AutoDetectedLinkUnderlineSpan::class.java)) {
|
||||
spannable.removeSpan(span)
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyVisualStyling(
|
||||
spannable: Spannable,
|
||||
start: Int,
|
||||
end: Int,
|
||||
style: InputFormatterStyle,
|
||||
) {
|
||||
spannable.setSpan(
|
||||
AutoDetectedLinkColorSpan(style.linkColor),
|
||||
start,
|
||||
end,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
|
||||
)
|
||||
if (style.linkUnderline) {
|
||||
spannable.setSpan(
|
||||
AutoDetectedLinkUnderlineSpan(),
|
||||
start,
|
||||
end,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val DEFAULT_PATTERN: Pattern =
|
||||
Pattern.compile(
|
||||
"(?:https?://[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-z]{2,6}\\b[-a-zA-Z0-9@:%_+.~#?&//=]*" +
|
||||
"|www\\.[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-z]{2,6}\\b[-a-zA-Z0-9@:%_+.~#?&//=]*" +
|
||||
"|[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-z]{2,6}\\b[-a-zA-Z0-9@:%_+.~#?&//=]*)",
|
||||
Pattern.CASE_INSENSITIVE,
|
||||
)
|
||||
|
||||
private fun normalizeUrl(url: String): String {
|
||||
if (url.startsWith("http://") || url.startsWith("https://")) return url
|
||||
return "https://$url"
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.swmansion.enriched.markdown.input.detection
|
||||
|
||||
import android.text.Spannable
|
||||
import com.swmansion.enriched.markdown.input.model.FormattingRange
|
||||
|
||||
/**
|
||||
* Coordinates a set of [TextDetector] instances. The input view calls
|
||||
* this pipeline instead of individual detectors.
|
||||
*/
|
||||
class DetectorPipeline {
|
||||
private val detectors = mutableListOf<TextDetector>()
|
||||
|
||||
fun addDetector(detector: TextDetector) {
|
||||
detectors.add(detector)
|
||||
}
|
||||
|
||||
fun processTextChange(
|
||||
spannable: Spannable,
|
||||
text: String,
|
||||
editStart: Int,
|
||||
editLength: Int,
|
||||
) {
|
||||
val words = WordsUtils.getAffectedWords(text, editStart, editLength)
|
||||
|
||||
for (wordResult in words) {
|
||||
for (detector in detectors) {
|
||||
detector.processWord(spannable, wordResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshAllStyling(spannable: Spannable) {
|
||||
for (detector in detectors) {
|
||||
detector.refreshStyling(spannable)
|
||||
}
|
||||
}
|
||||
|
||||
fun allTransientFormattingRanges(spannable: Spannable): List<FormattingRange> =
|
||||
detectors.flatMap { it.transientFormattingRanges(spannable) }
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.swmansion.enriched.markdown.input.detection
|
||||
|
||||
import android.text.Spannable
|
||||
import com.swmansion.enriched.markdown.input.model.FormattingRange
|
||||
|
||||
/**
|
||||
* Interface for pluggable text detectors that run after each text edit.
|
||||
* Each detector processes affected words, can refresh its own visual styling
|
||||
* after the formatter resets spans, and contributes transient formatting ranges
|
||||
* for markdown serialization.
|
||||
*/
|
||||
interface TextDetector {
|
||||
/** Process a single word at the given range after a text edit. */
|
||||
fun processWord(
|
||||
spannable: Spannable,
|
||||
wordResult: WordResult,
|
||||
)
|
||||
|
||||
/** Re-apply any visual styling owned by this detector. */
|
||||
fun refreshStyling(spannable: Spannable)
|
||||
|
||||
/**
|
||||
* Return transient formatting ranges that should be merged
|
||||
* with the FormattingStore ranges during markdown serialization.
|
||||
*/
|
||||
fun transientFormattingRanges(spannable: Spannable): List<FormattingRange>
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.swmansion.enriched.markdown.input.detection
|
||||
|
||||
data class WordResult(
|
||||
val word: String,
|
||||
val start: Int,
|
||||
val end: Int,
|
||||
)
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.swmansion.enriched.markdown.input.detection
|
||||
|
||||
object WordsUtils {
|
||||
/**
|
||||
* Returns the start index of the token (non-whitespace run) that ends at [position].
|
||||
* If [position] is directly after whitespace (or at the start of text), returns [position].
|
||||
*/
|
||||
fun tokenStart(
|
||||
text: String,
|
||||
position: Int,
|
||||
): Int {
|
||||
var start = position
|
||||
while (start > 0 && !text[start - 1].isWhitespace()) {
|
||||
start--
|
||||
}
|
||||
return start
|
||||
}
|
||||
|
||||
fun getAffectedWords(
|
||||
text: String,
|
||||
editStart: Int,
|
||||
editLength: Int,
|
||||
): List<WordResult> {
|
||||
val textLength = text.length
|
||||
if (textLength == 0) return emptyList()
|
||||
|
||||
var left = editStart.coerceIn(0, textLength)
|
||||
if (left > 0) {
|
||||
left--
|
||||
while (left > 0 && !text[left].isWhitespace()) {
|
||||
left--
|
||||
}
|
||||
if (text[left].isWhitespace()) left++
|
||||
}
|
||||
|
||||
var right = (editStart + editLength).coerceIn(0, textLength)
|
||||
if (right < textLength) {
|
||||
while (right < textLength && !text[right].isWhitespace()) {
|
||||
right++
|
||||
}
|
||||
}
|
||||
|
||||
if (left >= right) return emptyList()
|
||||
|
||||
val results = mutableListOf<WordResult>()
|
||||
var wordStart = left
|
||||
var i = left
|
||||
|
||||
while (i < right) {
|
||||
if (text[i].isWhitespace()) {
|
||||
if (i > wordStart) {
|
||||
results.add(WordResult(text.substring(wordStart, i), wordStart, i))
|
||||
}
|
||||
wordStart = i + 1
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
if (wordStart < right) {
|
||||
results.add(WordResult(text.substring(wordStart, right), wordStart, right))
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
package com.swmansion.enriched.markdown.input.editing
|
||||
|
||||
import android.text.Editable
|
||||
import com.swmansion.enriched.markdown.input.formatting.BlockStore
|
||||
import com.swmansion.enriched.markdown.input.model.BlockRange
|
||||
import com.swmansion.enriched.markdown.input.model.BlockType
|
||||
import com.swmansion.enriched.markdown.input.model.MAX_LIST_DEPTH
|
||||
|
||||
/**
|
||||
* Encapsulates block-editing operations: toggling block types, adjusting
|
||||
* list depth, and querying the block at a given position. The view delegates
|
||||
* here and applies UI-level consequences (formatting, anchor sync, cursor
|
||||
* size, typing attributes) based on the returned result.
|
||||
*
|
||||
* All mutating methods normalize stores to line bounds before returning, so
|
||||
* the caller can re-stamp block spans immediately.
|
||||
*/
|
||||
class BlockEditCoordinator(
|
||||
private val blockStore: BlockStore,
|
||||
) {
|
||||
// ── Queries ──────────────────────────────────────────────────────────
|
||||
|
||||
fun blockAtPosition(
|
||||
text: CharSequence,
|
||||
pos: Int,
|
||||
): BlockRange? {
|
||||
val lineStart = lineStartOf(text, pos)
|
||||
return blockStore.blockStartingAt(lineStart)
|
||||
}
|
||||
|
||||
fun listBlockAtPosition(
|
||||
text: CharSequence,
|
||||
pos: Int,
|
||||
): BlockRange? = blockAtPosition(text, pos)?.takeIf { it.type in BlockType.LIST_ITEMS }
|
||||
|
||||
fun listBlockAtLineStart(lineStart: Int): BlockRange? = blockStore.blockStartingAt(lineStart)?.takeIf { it.type in BlockType.LIST_ITEMS }
|
||||
|
||||
fun headingLevelAtPosition(
|
||||
text: CharSequence,
|
||||
pos: Int,
|
||||
): Int {
|
||||
val block = blockAtPosition(text, pos) ?: return 0
|
||||
return if (block.type in BlockType.HEADINGS) block.level else 0
|
||||
}
|
||||
|
||||
fun listStateAtPosition(
|
||||
text: CharSequence,
|
||||
pos: Int,
|
||||
type: BlockType,
|
||||
): Pair<Boolean, Int> {
|
||||
val block = listBlockAtPosition(text, pos) ?: return false to 0
|
||||
return if (block.type == type) true to block.level else false to 0
|
||||
}
|
||||
|
||||
// ── Mutations ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Toggles [type] at [level] on the paragraphs the selection touches.
|
||||
* Returns true when the block was already active (i.e. it was turned off).
|
||||
*/
|
||||
fun toggleBlock(
|
||||
text: Editable,
|
||||
type: BlockType,
|
||||
level: Int,
|
||||
selStart: Int,
|
||||
selEnd: Int,
|
||||
): Boolean {
|
||||
val existing = blockAtPosition(text, selStart)
|
||||
val wasActive = existing != null && existing.type == type && existing.level == level
|
||||
|
||||
if (wasActive) {
|
||||
blockStore.removeBlock(selStart, selEnd, text)
|
||||
} else {
|
||||
forEachLine(text, selStart, selEnd) { ls, le ->
|
||||
blockStore.setBlock(type, level, ls, le, text)
|
||||
}
|
||||
}
|
||||
blockStore.normalizeToLineBounds(text)
|
||||
return wasActive
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles a list of [type] on the selection: turns lines into depth-0
|
||||
* items (switching list type keeps each line's depth) or clears them back
|
||||
* to plain paragraphs when the cursor line already carries [type].
|
||||
* Returns true when the list was turned off.
|
||||
*/
|
||||
fun toggleList(
|
||||
text: Editable,
|
||||
type: BlockType,
|
||||
cursorPos: Int,
|
||||
selStart: Int,
|
||||
selEnd: Int,
|
||||
): Boolean {
|
||||
val turningOff = listBlockAtPosition(text, cursorPos)?.type == type
|
||||
if (turningOff) {
|
||||
forEachLine(text, selStart, selEnd) { ls, le ->
|
||||
blockStore.removeBlock(ls, le, text)
|
||||
}
|
||||
} else {
|
||||
forEachLine(text, selStart, selEnd) { ls, le ->
|
||||
val existing = listBlockAtLineStart(ls)
|
||||
blockStore.setBlock(type, existing?.level ?: 0, ls, le, text)
|
||||
}
|
||||
}
|
||||
blockStore.normalizeToLineBounds(text)
|
||||
return turningOff
|
||||
}
|
||||
|
||||
enum class DepthChangeResult {
|
||||
/** Depth was adjusted on the existing list item(s). */
|
||||
CHANGED,
|
||||
|
||||
/** No list existed; a new unordered list was started (delta > 0 only). */
|
||||
STARTED_LIST,
|
||||
|
||||
/** Outdented at depth 0 — the list marker was removed. */
|
||||
EXITED_LIST,
|
||||
|
||||
/** Nothing happened (e.g. outdent on a heading or plain paragraph). */
|
||||
NO_OP,
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjusts list depth by [delta] on the selected lines. When the cursor
|
||||
* is on a plain paragraph and delta > 0, starts a new unordered list.
|
||||
* When outdenting at depth 0, removes the list marker.
|
||||
*
|
||||
* Returns the action taken so the view can apply the appropriate UI effects.
|
||||
*/
|
||||
fun changeDepth(
|
||||
text: Editable,
|
||||
cursorPos: Int,
|
||||
selStart: Int,
|
||||
selEnd: Int,
|
||||
delta: Int,
|
||||
): DepthChangeResult {
|
||||
val cursorBlock = listBlockAtPosition(text, cursorPos)
|
||||
if (cursorBlock == null) {
|
||||
if (delta > 0 && blockAtPosition(text, cursorPos) == null) {
|
||||
toggleList(text, BlockType.UNORDERED_LIST_ITEM, cursorPos, selStart, selEnd)
|
||||
return DepthChangeResult.STARTED_LIST
|
||||
}
|
||||
return DepthChangeResult.NO_OP
|
||||
}
|
||||
if (delta < 0 && cursorBlock.level == 0) {
|
||||
toggleList(text, cursorBlock.type, cursorPos, selStart, selEnd)
|
||||
return DepthChangeResult.EXITED_LIST
|
||||
}
|
||||
|
||||
forEachLine(text, selStart, selEnd) { ls, _ ->
|
||||
val block = listBlockAtLineStart(ls)
|
||||
if (block != null) {
|
||||
val newDepth = (block.level + delta).coerceIn(0, MAX_LIST_DEPTH)
|
||||
blockStore.setBlock(block.type, newDepth, ls, ls, text)
|
||||
}
|
||||
}
|
||||
blockStore.normalizeToLineBounds(text)
|
||||
return DepthChangeResult.CHANGED
|
||||
}
|
||||
|
||||
// ── Line utilities ───────────────────────────────────────────────────
|
||||
|
||||
fun lineStartOf(
|
||||
text: CharSequence,
|
||||
pos: Int,
|
||||
): Int {
|
||||
var s = pos.coerceIn(0, text.length)
|
||||
while (s > 0 && !text[s - 1].isLineBreak()) s--
|
||||
return s
|
||||
}
|
||||
|
||||
fun lineEndOf(
|
||||
text: CharSequence,
|
||||
pos: Int,
|
||||
): Int {
|
||||
var e = pos.coerceIn(0, text.length)
|
||||
while (e < text.length && !text[e].isLineBreak()) e++
|
||||
return e
|
||||
}
|
||||
|
||||
private inline fun forEachLine(
|
||||
text: CharSequence,
|
||||
selStart: Int,
|
||||
selEnd: Int,
|
||||
action: (lineStart: Int, lineEnd: Int) -> Unit,
|
||||
) {
|
||||
var cursor = lineStartOf(text, selStart)
|
||||
while (cursor <= text.length) {
|
||||
val le = lineEndOf(text, cursor)
|
||||
action(cursor, le)
|
||||
if (le >= selEnd) break
|
||||
cursor = le + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user