diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.md
index 729339cfa8..1baadffb4d 100644
--- a/.agents/skills/writing-tests/SKILL.md
+++ b/.agents/skills/writing-tests/SKILL.md
@@ -16,7 +16,7 @@ The file extension is the discriminator, never a `.browser` suffix:
- `*.test-d.ts` is type-level, using `expectTypeOf` from vitest
- `gherkin-tests/*.feature` + racejar for behavior specs (`Feature({featureText, stepDefinitions, parameterTypes})`)
-When scaffolding a new package, mirror `plugin-sdk-value`'s vitest config: a `browser` project including `src/**/*.test.tsx` and a `unit` project including `src/**/*.test.ts`.
+When scaffolding a new package, mirror `plugin-paste-link`'s vitest config: a `browser` project including `src/**/*.test.tsx` and a `unit` project including `src/**/*.test.ts`.
## Choosing the form
diff --git a/README.md b/README.md
index 456d8ecaa3..3d2f51121b 100644
--- a/README.md
+++ b/README.md
@@ -40,7 +40,7 @@ For documentation and guides, visit [portabletext.org](https://www.portabletext.
| [`@portabletext/plugin-markdown-shortcuts`](./packages/plugin-markdown-shortcuts/) | Add helpful Markdown shortcuts to the editor |
| [`@portabletext/plugin-one-line`](./packages/plugin-one-line/) | Restrict the Portable Text Editor to a single line |
| [`@portabletext/plugin-paste-link`](./packages/plugin-paste-link/) | Allow pasting links in the Portable Text Editor |
-| [`@portabletext/plugin-sdk-value`](./packages/plugin-sdk-value/) | Connect a Portable Text Editor with a Sanity document using the SDK |
+| [`@portabletext/plugin-sdk-value`](https://github.com/portabletext/plugin-sdk-value) | Connect a Portable Text Editor with a Sanity document using the SDK |
| [`@portabletext/plugin-table`](./packages/plugin-table/) | Tables as real Portable Text, edited with spreadsheet-grade selection |
| [`@portabletext/plugin-typeahead-picker`](./packages/plugin-typeahead-picker/) | Build typeahead pickers (emoji, mentions, slash commands) |
| [`@portabletext/plugin-typography`](./packages/plugin-typography/) | Automatically transform text to typographic variants |
diff --git a/apps/doc-examples/package.json b/apps/doc-examples/package.json
index 0dd73a04f4..2c5f69e5bd 100644
--- a/apps/doc-examples/package.json
+++ b/apps/doc-examples/package.json
@@ -23,7 +23,6 @@
"@portabletext/plugin-markdown-shortcuts": "workspace:*",
"@portabletext/plugin-one-line": "workspace:*",
"@portabletext/plugin-paste-link": "workspace:*",
- "@portabletext/plugin-sdk-value": "workspace:*",
"@portabletext/plugin-table": "workspace:*",
"@portabletext/plugin-typeahead-picker": "workspace:*",
"@portabletext/plugin-typography": "workspace:*",
diff --git a/apps/docs/src/content/docs/ecosystem/packages.mdx b/apps/docs/src/content/docs/ecosystem/packages.mdx
index b17cf79b0d..7a8a2710b0 100644
--- a/apps/docs/src/content/docs/ecosystem/packages.mdx
+++ b/apps/docs/src/content/docs/ecosystem/packages.mdx
@@ -71,7 +71,7 @@ Serializers convert Portable Text JSON into your target output.
| [`@portabletext/plugin-markdown-shortcuts`](https://github.com/portabletext/editor/tree/main/packages/plugin-markdown-shortcuts) | Markdown-style shortcuts in the editor | `npm i @portabletext/plugin-markdown-shortcuts` |
| [`@portabletext/plugin-one-line`](https://github.com/portabletext/editor/tree/main/packages/plugin-one-line) | Restrict editor to a single line | `npm i @portabletext/plugin-one-line` |
| [`@portabletext/plugin-paste-link`](https://github.com/portabletext/editor/tree/main/packages/plugin-paste-link) | Paste URLs as links | `npm i @portabletext/plugin-paste-link` |
-| [`@portabletext/plugin-sdk-value`](https://github.com/portabletext/editor/tree/main/packages/plugin-sdk-value) | Syncs editor value with the Sanity SDK | `npm i @portabletext/plugin-sdk-value` |
+| [`@portabletext/plugin-sdk-value`](https://github.com/portabletext/plugin-sdk-value) | Syncs editor value with the Sanity SDK | `npm i @portabletext/plugin-sdk-value` |
| [`@portabletext/plugin-table`](https://github.com/portabletext/editor/tree/main/packages/plugin-table) | Table editing with spreadsheet-grade selection | `npm i @portabletext/plugin-table` |
| [`@portabletext/plugin-typeahead-picker`](https://github.com/portabletext/editor/tree/main/packages/plugin-typeahead-picker) | Typeahead/autocomplete picker infrastructure | `npm i @portabletext/plugin-typeahead-picker` |
| [`@portabletext/plugin-typography`](https://github.com/portabletext/editor/tree/main/packages/plugin-typography) | Smart quotes, em dashes, ellipses | `npm i @portabletext/plugin-typography` |
diff --git a/apps/docs/src/content/docs/editor/reference/plugins.mdx b/apps/docs/src/content/docs/editor/reference/plugins.mdx
index 5bd83473c3..9c94600f47 100644
--- a/apps/docs/src/content/docs/editor/reference/plugins.mdx
+++ b/apps/docs/src/content/docs/editor/reference/plugins.mdx
@@ -129,7 +129,7 @@ function LogImagesPlugin() {
({root, importTime: false})),
diff --git a/knip.json b/knip.json
index fdd722e3ad..b9264bbb16 100644
--- a/knip.json
+++ b/knip.json
@@ -110,7 +110,6 @@
"@portabletext/plugin-markdown-shortcuts",
"@portabletext/plugin-one-line",
"@portabletext/plugin-paste-link",
- "@portabletext/plugin-sdk-value",
"@portabletext/plugin-table",
"@portabletext/plugin-typeahead-picker",
"@portabletext/plugin-typography",
diff --git a/packages/editor/test-utils/diff-value-patches.ts b/packages/editor/test-utils/diff-value-patches.ts
index 75657f861c..695a17b171 100644
--- a/packages/editor/test-utils/diff-value-patches.ts
+++ b/packages/editor/test-utils/diff-value-patches.ts
@@ -20,7 +20,7 @@ import {
* `diffValue`-into-patches through the one applier).
*
* Keep in sync with `convertPatches`/`arrayifyPath` in
- * `packages/plugin-sdk-value/src/plugin.sdk-value.tsx`, the same translation
+ * `@portabletext/plugin-sdk-value` (`src/plugin.sdk-value.tsx`), the same translation
* used by the SDK plugin's repair path. Deliberately duplicated (test-only,
* for now) instead of exported.
*/
diff --git a/packages/plugin-sdk-value/CHANGELOG.md b/packages/plugin-sdk-value/CHANGELOG.md
deleted file mode 100644
index 9e4554ef92..0000000000
--- a/packages/plugin-sdk-value/CHANGELOG.md
+++ /dev/null
@@ -1,1682 +0,0 @@
-# Changelog
-
-## 8.1.20
-
-### Patch Changes
-
-- Updated dependencies [[`3729248`](https://github.com/portabletext/editor/commit/3729248acac220c3a5327ad9b85b6faf69aeda4d)]:
- - @portabletext/patches@3.0.4
-
-## 8.1.19
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.2.11`
-
-## 8.1.18
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.2.10`
-
-## 8.1.17
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.2.9`
-
-## 8.1.16
-
-### Patch Changes
-
-- Updated dependencies [[`91e6bcb`](https://github.com/portabletext/editor/commit/91e6bcbe8871bd2af96de15ca6b279895dbdf2ea), [`59d4ee0`](https://github.com/portabletext/editor/commit/59d4ee0cf130ca791a3d4f7474d175b53c7a40a6)]:
- - @portabletext/patches@3.0.3
-
-## 8.1.15
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.2.7`
-
-## 8.1.14
-
-### Patch Changes
-
-- [#3260](https://github.com/portabletext/editor/pull/3260) [`dabaea4`](https://github.com/portabletext/editor/commit/dabaea4a182054032a83324799a1d480cd2b7c9e) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update react to ^19.3.1
-- Updated dependencies [[`a2c9bb2`](https://github.com/portabletext/editor/commit/a2c9bb2d59f87d50387526314e9578c030d5a5ee)]:
- - @portabletext/patches@3.0.2
-
-## 8.1.13
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.2.5`
-
-## 8.1.12
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.2.4`
-
-## 8.1.11
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.2.3`
-
-## 8.1.10
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.2.2`
-
-## 8.1.9
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.2.1`
-
-## 8.1.8
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.2.0`
-
-## 8.1.7
-
-### Patch Changes
-
-- [#3303](https://github.com/portabletext/editor/pull/3303) [`47adf66`](https://github.com/portabletext/editor/commit/47adf660f2d92b03c4f31af247e64bacaa6beb99) Thanks [@christianhg](https://github.com/christianhg)! - fix(deps): replace `debug` with `obug`
-
- Both packages now pull in `obug`, an actively maintained ESM/TypeScript fork of `debug`, instead of `debug` itself. Debug output is unchanged: the same namespaces (`pte:*`, `pte:plugin-sdk-value:*`) are still enabled the same way, via the `DEBUG` environment variable in Node.js or `localStorage.debug` in browsers. `@types/debug` is no longer installed alongside it, since `obug` ships its own types.
-
-## 8.1.6
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.1.7`
-
-## 8.1.5
-
-### Patch Changes
-
-- [#3290](https://github.com/portabletext/editor/pull/3290) [`0f95709`](https://github.com/portabletext/editor/commit/0f95709d8038a4fc6768758ae11fae6e246c0be0) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @sanity/diff-match-patch to ^3.2.1
-
-- Updated dependencies [[`0f95709`](https://github.com/portabletext/editor/commit/0f95709d8038a4fc6768758ae11fae6e246c0be0)]:
- - @portabletext/patches@3.0.1
-
-## 8.1.4
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.1.5`
-
-## 8.1.3
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.1.4`
-
-## 8.1.2
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.1.3`
-
-## 8.1.1
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.1.2`
-
-## 8.1.0
-
-### Minor Changes
-
-- [#3159](https://github.com/portabletext/editor/pull/3159) [`2e325bf`](https://github.com/portabletext/editor/commit/2e325bf963c5a88301cd04840ad4c7e4773b39db) Thanks [@ryanbonial](https://github.com/ryanbonial)! - feat: add inline comment decorations and authoring
-
- Two new hooks bring Sanity's inline comments to SDK apps that embed the editor. `useSDKCommentDecorations` returns `RangeDecoration[]` for the open comment threads anchored to text in the field; pass it to `SDKPortableTextEditable` (or a raw `PortableTextEditable`) through `rangeDecorations`:
-
- ```tsx
- const decorations = useSDKCommentDecorations({
- ...documentHandle,
- path: 'content',
- renderDecoration: (comment) => (props) => (
-
- {props.children}
-
- ),
- })
-
- return (
-
- )
- ```
-
- `useSDKCommentAuthoring` is the write side: `commentableSelection` is set when the current selection can take a comment, and `createInlineComment` starts a thread anchored to that selection:
-
- ```tsx
- const {commentableSelection, createInlineComment} = useSDKCommentAuthoring({
- ...documentHandle,
- path: 'content',
- })
- // show the composer while `commentableSelection` is set, then:
- await createInlineComment({message})
- ```
-
- The types their signatures reference (`UseSDKCommentDecorationsOptions`, `RenderCommentDecorationFunction`, `UseSDKCommentAuthoringOptions`, `SDKCommentAuthoring`) are exported alongside them.
-
- Highlights follow the text while the user types, and a highlight whose text is deleted or rewritten beyond recognition is dropped rather than drawn on the wrong words. Comments are written in the shape Sanity Studio stores, so threads round-trip between an SDK app and the Studio. The composer UI is the app's to render, the same split presence uses for carets. Requires `@sanity/sdk-react` 2.20.1 or later.
-
-## 8.0.6
-
-### Patch Changes
-
-- [#3212](https://github.com/portabletext/editor/pull/3212) [`f5feeea`](https://github.com/portabletext/editor/commit/f5feeea73c9f105760ddb6c8a41ce91fcfc6c74a) Thanks [@rexxars](https://github.com/rexxars)! - fix: support `@sanity/sdk-react` 3 with normalized document handles
-
- `@portabletext/plugin-sdk-value` now supports `@sanity/sdk-react` 3 in addition to 2.19 and later. The removed `source` document-handle alias is translated to `resource`, so existing integrations do not need code changes.
-
-## 8.0.5
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.1.1`
-
-## 8.0.4
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.1.0`
-
-## 8.0.3
-
-### Patch Changes
-
-- fix(deps): require `@portabletext/editor@^8.0.3`
-
-## 8.0.2
-
-### Patch Changes
-
-- Updated dependencies [[`b5739d5`](https://github.com/portabletext/editor/commit/b5739d55389ed2b47546cb5309a237c353d8335c)]:
- - @portabletext/editor@8.0.2
-
-## 8.0.1
-
-### Patch Changes
-
-- Updated dependencies [[`34717cf`](https://github.com/portabletext/editor/commit/34717cf511de9485b265ce53eec57be5eaf07d95)]:
- - @portabletext/editor@8.0.1
-
-## 8.0.0
-
-### Major Changes
-
-- [#3110](https://github.com/portabletext/editor/pull/3110) [`09aa881`](https://github.com/portabletext/editor/commit/09aa8813211bc26d1a75f94a2ff619fae6e132cb) Thanks [@christianhg](https://github.com/christianhg)! - feat!: drop the legacy `main` and `module` fields
-
- Every package now declares its entry points through the `exports` map only. Node, all maintained bundlers, and TypeScript (`moduleResolution: 'bundler'`, 'node16', or 'nodenext') resolve through `exports`; only tooling that predates `exports` support read `main` or `module` and can no longer resolve these packages.
-
-- [#3106](https://github.com/portabletext/editor/pull/3106) [`3ce5a1d`](https://github.com/portabletext/editor/commit/3ce5a1d00caec9593a4f8d240d05df90505ca655) Thanks [@christianhg](https://github.com/christianhg)! - feat!: require node 22.12 or later
-
- Node.js 22.12 or later is now required. The previous range also allowed Node.js 20.19 and later; Node.js 20 reached end of life in April 2026 and is no longer supported. `@portabletext/editor` and `@portabletext/markdown` also move to `@portabletext/to-html` v6 and `@portabletext/toolkit` v6, which carry the same Node.js requirement.
-
-### Patch Changes
-
-- Updated dependencies [[`09aa881`](https://github.com/portabletext/editor/commit/09aa8813211bc26d1a75f94a2ff619fae6e132cb), [`7718cf0`](https://github.com/portabletext/editor/commit/7718cf049b96fd8d3461211bc1dabc7bbcbb81f8), [`bf3373a`](https://github.com/portabletext/editor/commit/bf3373ae78698ab0dd69f2705bde864732d03e18), [`59d71ca`](https://github.com/portabletext/editor/commit/59d71ca58eeb1289f0cef65b8fde3841bbcb99e0), [`7892af2`](https://github.com/portabletext/editor/commit/7892af22d1144f2ebe32fb6f857c671330c6ab6a), [`2db496d`](https://github.com/portabletext/editor/commit/2db496dc53c22b7961d1121009032145429b9653), [`e2d081e`](https://github.com/portabletext/editor/commit/e2d081e5b9a257ec09299d8e2f9f0b9389fdc7a6), [`09c5741`](https://github.com/portabletext/editor/commit/09c5741b4a8186f64fa5523e5324b751c051d1ad), [`83a0438`](https://github.com/portabletext/editor/commit/83a04382ed4f79bec3b4cf8e741e4478c68b7f6f), [`3ce5a1d`](https://github.com/portabletext/editor/commit/3ce5a1d00caec9593a4f8d240d05df90505ca655), [`73cf0e1`](https://github.com/portabletext/editor/commit/73cf0e1b48d35dbfc348d8556154a61a7890dde3), [`6fde634`](https://github.com/portabletext/editor/commit/6fde634789e87f97d42d428d823e1cbc4f060367), [`fe7de91`](https://github.com/portabletext/editor/commit/fe7de913129d807c0e05464c0df33dc6a189e0e2)]:
- - @portabletext/editor@8.0.0
- - @portabletext/patches@3.0.0
-
-## 7.2.6
-
-### Patch Changes
-
-- Updated dependencies [[`e6a55a9`](https://github.com/portabletext/editor/commit/e6a55a9918e7ca78c5d3e9a2ef95854ec2df2e66), [`51e4bfe`](https://github.com/portabletext/editor/commit/51e4bfe39f7e25fd1d36305a95b5816ae02e7126)]:
- - @portabletext/editor@7.12.0
-
-## 7.2.5
-
-### Patch Changes
-
-- Updated dependencies [[`5c61867`](https://github.com/portabletext/editor/commit/5c618674c28627ad742f326076d9e27d4a09ddf1), [`9e3b7be`](https://github.com/portabletext/editor/commit/9e3b7be9cf95772a32724acea69cee233f0d9f9f), [`fbb9a98`](https://github.com/portabletext/editor/commit/fbb9a9824dcea07aad66a4c69bb33db6c3fe0be8), [`2c97777`](https://github.com/portabletext/editor/commit/2c97777c56746a418b582258268b452b6168a32b), [`2f5c148`](https://github.com/portabletext/editor/commit/2f5c148b42a0f1dc5c1efb535ca4afd680e831b0), [`e7df9b8`](https://github.com/portabletext/editor/commit/e7df9b8ffcf51f984bb14439dbeaaa9a348b9b45), [`eb8cb6c`](https://github.com/portabletext/editor/commit/eb8cb6cff6c793e107cc1d5f4c85b78ba565b74b), [`75d2dc4`](https://github.com/portabletext/editor/commit/75d2dc4ddfd5ae7f6be0630339d5fb34f6e0a750), [`45fd070`](https://github.com/portabletext/editor/commit/45fd0706b72b92e5a663bdc019e1e464972eafb5), [`bfd7058`](https://github.com/portabletext/editor/commit/bfd7058700754ba7ac5af35aae99b2bc8ce70dfb), [`8c72f76`](https://github.com/portabletext/editor/commit/8c72f7622108f406d7930a9905f9c517a2e9c181), [`db10bb7`](https://github.com/portabletext/editor/commit/db10bb7a3659f02d11b8aca5cc2424e62314faec)]:
- - @portabletext/editor@7.11.0
-
-## 7.2.4
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@7.10.19
-
-## 7.2.3
-
-### Patch Changes
-
-- [#3012](https://github.com/portabletext/editor/pull/3012) [`94b4106`](https://github.com/portabletext/editor/commit/94b4106a22fd44096fd8b8bcc594ebf8918ff60d) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update react to ^19.2.8
-
-- [#3060](https://github.com/portabletext/editor/pull/3060) [`5f073b5`](https://github.com/portabletext/editor/commit/5f073b53ae184606e52cb52567f688c7805a7515) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency xstate to ^5.32.5
-
-- Updated dependencies [[`94b4106`](https://github.com/portabletext/editor/commit/94b4106a22fd44096fd8b8bcc594ebf8918ff60d), [`5f073b5`](https://github.com/portabletext/editor/commit/5f073b53ae184606e52cb52567f688c7805a7515)]:
- - @portabletext/editor@7.10.18
-
-## 7.2.2
-
-### Patch Changes
-
-- [#3042](https://github.com/portabletext/editor/pull/3042) [`cddbf04`](https://github.com/portabletext/editor/commit/cddbf041ded81ac7fe3ee6e5aed0869f014f420c) Thanks [@stipsan](https://github.com/stipsan)! - fix: add a `module` entry point
-
- Every package now declares `module` alongside `main`, pointing at the ESM build.
- Bundlers that predate `exports` use it to pick the ESM output instead of falling
- back to `main`.
-
-- Updated dependencies [[`7e1bc11`](https://github.com/portabletext/editor/commit/7e1bc11554247318356aef8f36151763674c6dcb), [`cddbf04`](https://github.com/portabletext/editor/commit/cddbf041ded81ac7fe3ee6e5aed0869f014f420c), [`cddbf04`](https://github.com/portabletext/editor/commit/cddbf041ded81ac7fe3ee6e5aed0869f014f420c), [`46c019c`](https://github.com/portabletext/editor/commit/46c019cc3ae1112c1027059b06d80432fd2ca1d7)]:
- - @portabletext/editor@7.10.17
- - @portabletext/patches@2.0.6
-
-## 7.2.1
-
-### Patch Changes
-
-- Updated dependencies [[`b18469f`](https://github.com/portabletext/editor/commit/b18469f7c73ef036c633142f3864ed16a70fa93c)]:
- - @portabletext/editor@7.10.16
-
-## 7.2.0
-
-### Minor Changes
-
-- [#3036](https://github.com/portabletext/editor/pull/3036) [`fd68074`](https://github.com/portabletext/editor/commit/fd6807457c39bc92c2fb5bce5018bb5742d07856) Thanks [@ryanbonial](https://github.com/ryanbonial)! - feat: add presence, and `SDKPortableTextEditable`
-
- Other people's carets now show up in a Portable Text field, and the local user's caret is reported so they show up elsewhere, including in the Studio.
-
- `SDKPortableTextEditable` replaces `PortableTextEditable` and does all of it: value sync both ways, presence reporting, and drawing remote carets. It names the document and field once, so a separate `SDKValuePlugin` is no longer needed. Any `rangeDecorations` you pass are kept and merged with the presence carets rather than replaced.
-
- Remote carets are drawn with a built-in caret component, so presence works without styling anything. Pass `renderCursor` to replace it, or `renderCursor={null}` to report presence without drawing carets.
-
- `SDKPresencePlugin` and `useSDKPresenceCursors` are available for apps that render `PortableTextEditable` themselves.
-
- The `@sanity/sdk-react` peer range moves to `^2.19.0`, which is where the presence hooks were added.
-
-### Patch Changes
-
-- [#3033](https://github.com/portabletext/editor/pull/3033) [`6b2c0c8`](https://github.com/portabletext/editor/commit/6b2c0c8b923237a4c42164be7fb1bd103aecee4d) Thanks [@christianhg](https://github.com/christianhg)! - fix: stop concurrent annotation edits from duplicating mark definitions
-
- When two people annotated at the same time, the same mark definition could be saved into the document twice. When the sync layer re-sends a definition it now replaces its earlier copy instead of adding a second one.
-
-- Updated dependencies [[`520e1be`](https://github.com/portabletext/editor/commit/520e1bebae3aa6853262b66775f9e941217c7eaf), [`ff7e095`](https://github.com/portabletext/editor/commit/ff7e095f681967031bd84d586a7a0f0f7a27e671), [`03a0aaa`](https://github.com/portabletext/editor/commit/03a0aaa8861debda4d1ba81f8af3b3e73409588d)]:
- - @portabletext/editor@7.10.15
-
-## 7.1.7
-
-### Patch Changes
-
-- Updated dependencies [[`04bc38e`](https://github.com/portabletext/editor/commit/04bc38ebc01a7dad7824bf1654306186475364af)]:
- - @portabletext/editor@7.10.14
-
-## 7.1.6
-
-### Patch Changes
-
-- [#3025](https://github.com/portabletext/editor/pull/3025) [`92ecb55`](https://github.com/portabletext/editor/commit/92ecb55baacf700a25bef710563dde8676f839cf) Thanks [@ryanbonial](https://github.com/ryanbonial)! - fix: prevent remote decorator toggles from transiently dropping the formatted word
-
-## 7.1.5
-
-### Patch Changes
-
-- [#3017](https://github.com/portabletext/editor/pull/3017) [`9619f58`](https://github.com/portabletext/editor/commit/9619f58cffdba0857aff504a31349fa66cabb0b1) Thanks [@ryanbonial](https://github.com/ryanbonial)! - fix: prevent transient duplicate text after a remote paste
-
-- Updated dependencies [[`68b5d17`](https://github.com/portabletext/editor/commit/68b5d174f5be776c4e9304ba53af0ef95e60ee3b)]:
- - @portabletext/editor@7.10.13
-
-## 7.1.4
-
-### Patch Changes
-
-- Updated dependencies [[`5ddcc5b`](https://github.com/portabletext/editor/commit/5ddcc5b42ec2560cde1650489d9219212c5d67b1), [`c600e92`](https://github.com/portabletext/editor/commit/c600e92bb94ec52762f63983bbd48f7b64654bfb)]:
- - @portabletext/editor@7.10.12
-
-## 7.1.3
-
-### Patch Changes
-
-- Updated dependencies [[`86bf426`](https://github.com/portabletext/editor/commit/86bf426af85f54c3acab61bffa3e3bfa8d976d5b)]:
- - @portabletext/editor@7.10.11
-
-## 7.1.2
-
-### Patch Changes
-
-- [#2998](https://github.com/portabletext/editor/pull/2998) [`2a71da1`](https://github.com/portabletext/editor/commit/2a71da159f50305a4a881a7d1bd7a0f473d16e88) Thanks [@ryanbonial](https://github.com/ryanbonial)! - fix: only repair divergence that persists, never transient store states
-
- With two users typing simultaneously (even in different blocks), a remote
- transaction arriving interleaved with the listener echoes of this client's
- own recent edits leaves the store value transiently wrong until the rebase
- corrects it moments later. The whole-value repair used to fire inside that
- window: it copied the transient into the editor (deleting real text) and a
- follow-up repair restored the text at a drifted offset, scrambling words
- the user typed in between.
-
- The repair now confirms divergence before acting: it waits out the echo
- round trip and only applies when the exact (editor, store) state pair is
- unchanged, and never while local keystrokes are unflushed. Transients
- self-correct and produce no editor writes; genuine divergence is stable
- and gets repaired one beat later.
-
-- [#2992](https://github.com/portabletext/editor/pull/2992) [`96f3a0e`](https://github.com/portabletext/editor/commit/96f3a0e6ca7d59efdac5696aac2aabfe88a18a12) Thanks [@christianhg](https://github.com/christianhg)! - fix: route sync diagnostics through the `debug` library
-
- The sync diagnostics channel is now enabled with `localStorage.debug = 'pte:plugin-sdk-value:*'` (before load) instead of the `globalThis.__PTE_SYNC_DEBUG` flag, which is removed. The log kinds become individually filterable namespaces (`pte:plugin-sdk-value:repair`, `:push`, `:remote`, `:mutation`), and enabling `pte:*` interleaves them with the editor's own debug output on one timeline. The channel stays free when disabled.
-
-- Updated dependencies [[`1aea458`](https://github.com/portabletext/editor/commit/1aea458849ecbb2ee5c88e97bfba1fc0ab6adbc7)]:
- - @portabletext/editor@7.10.10
-
-## 7.1.1
-
-### Patch Changes
-
-- [#2986](https://github.com/portabletext/editor/pull/2986) [`5f116f6`](https://github.com/portabletext/editor/commit/5f116f6c94c5f3ae837af825adfab1d5b7e787f1) Thanks [@ryanbonial](https://github.com/ryanbonial)! - fix: stop dropping mutation flushes and stomping in-flight typing during sync
-
- A single user typing (especially deleting and retyping) could see text
- reordered, duplicated, or resurrected. Two sync-machine bugs compounded:
- mutation flush events arriving in bursts were silently dropped by states
- without a handler, permanently diverging the store from the editor, and the
- whole-value repair ran while local edits were still in flight, diffing the
- editor against the lagging store and injecting stale text back into it.
-
- Every state now pushes mutation flushes, and the whole-value repair only
- runs when the editor is quiescent (on a store change while idle, plus a
- one-shot repair after a short idle delay).
-
-- Updated dependencies [[`fae7074`](https://github.com/portabletext/editor/commit/fae7074fb1617a7da35bb22a1a18e473ce1cc0b9), [`1676271`](https://github.com/portabletext/editor/commit/16762713632e5fe66e6a58f9214cc9ccd89e6f31), [`6592c0d`](https://github.com/portabletext/editor/commit/6592c0d82742c28bd2f4f27f78997456653bd8c8)]:
- - @portabletext/editor@7.10.9
-
-## 7.1.0
-
-### Minor Changes
-
-- [#2977](https://github.com/portabletext/editor/pull/2977) [`f7c1476`](https://github.com/portabletext/editor/commit/f7c1476189f7166c23029cc8c9c364b6d79af7ba) Thanks [@ryanbonial](https://github.com/ryanbonial)! - Sync through operational patches instead of whole-value diffs when the SDK supports it.
-
- `SDKValuePlugin` now subscribes to the SDK's `remote-patches` document events and applies patches from other clients directly to the editor, and pushes the editor's own patches back through `editDocument` with `preserveOperations`. This lets two people edit the same Portable Text field concurrently without overwriting each other. Whole-value sync remains as a fallback for SDK versions without the patch channel (`@sanity/sdk-react` < 2.17) and for patches that cannot be scoped to the field.
-
- `ValueSyncPlugin` accepts optional `onRemotePatches` and `pushPatches` config to drive the same behavior with a custom store.
-
-### Patch Changes
-
-- [#2977](https://github.com/portabletext/editor/pull/2977) [`f7c1476`](https://github.com/portabletext/editor/commit/f7c1476189f7166c23029cc8c9c364b6d79af7ba) Thanks [@ryanbonial](https://github.com/ryanbonial)! - Repair editor divergence after best-effort remote patch application, and make the patch channel safe under concurrent formatting.
-
- Applying remote patches is best-effort: keyed operations produced by another client against a different view of the document (for example both clients splitting the same span to format overlapping ranges) can fail to resolve, leaving the editor diverged from the stored document. `ValueSyncPlugin` now follows every remote patch application with a whole-value repair sync, immediately when no local edits are in flight or after the next mutation flush when they are, and escalates to the full value sync machinery when the diff-based repair cannot converge.
-
- Concurrent-editing hardening, validated against a live two-tab harness driving a real Content Lake dataset:
-
- - Remote patches are pre-flight checked against the local editor tree; operations addressing nodes that don't exist locally are dropped and left to the repair sync instead of being sent into the engine where they fail loudly.
- - Repair diffs (and incoming patches) addressing items inside sidecar arrays (`markDefs`, `marks`), which the engine cannot resolve, are coalesced into whole-property sets taken from the store value.
- - Outgoing `markDefs` whole-array sets are decomposed into item-keyed insert/set/unset operations so two clients' annotations merge at the server instead of overwriting each other, and definitions the stored document still references are never pruned by a diverged client (which orphaned the other client's marks).
- - An editor emptied by concurrent deletions writes `set(field, [])` instead of unsetting the whole field, which left other clients unable to reconcile.
- - Unconvertible diff paths (array slices such as `marks[1:]`) no longer throw an uncaught error that froze the sync actor; they fall back to the full value sync.
-
-## 7.0.35
-
-### Patch Changes
-
-- Updated dependencies [[`32c622e`](https://github.com/portabletext/editor/commit/32c622eb6c377a28646195ada69e8a47d30bb690)]:
- - @portabletext/editor@7.10.8
-
-## 7.0.34
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@7.10.7
-
-## 7.0.33
-
-### Patch Changes
-
-- Updated dependencies [[`44fd221`](https://github.com/portabletext/editor/commit/44fd221b6e2e13d6debda5d443f9f4ec596dca50)]:
- - @portabletext/editor@7.10.6
-
-## 7.0.32
-
-### Patch Changes
-
-- Updated dependencies [[`c94a206`](https://github.com/portabletext/editor/commit/c94a206be68bf35ec3db9b9b260ff82ee50ef3d9)]:
- - @portabletext/editor@7.10.5
-
-## 7.0.31
-
-### Patch Changes
-
-- Updated dependencies [[`e3997a4`](https://github.com/portabletext/editor/commit/e3997a4f8d86304767d0ba0eafb2845be126dd9a), [`3e199ef`](https://github.com/portabletext/editor/commit/3e199ef38b969b5c993e16466872a561de0e6e0f)]:
- - @portabletext/editor@7.10.4
-
-## 7.0.30
-
-### Patch Changes
-
-- [#2939](https://github.com/portabletext/editor/pull/2939) [`b1bb99e`](https://github.com/portabletext/editor/commit/b1bb99e06b6af10914578e86ae325addce8a0016) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency xstate to ^5.32.4
-
-- Updated dependencies [[`b1bb99e`](https://github.com/portabletext/editor/commit/b1bb99e06b6af10914578e86ae325addce8a0016)]:
- - @portabletext/editor@7.10.3
-
-## 7.0.29
-
-### Patch Changes
-
-- Updated dependencies [[`b339b25`](https://github.com/portabletext/editor/commit/b339b254444512d8de9a92eeb4773fb2777c4f96), [`2be9720`](https://github.com/portabletext/editor/commit/2be972078e0936bc7b52d4384edf723291faa47c)]:
- - @portabletext/editor@7.10.2
-
-## 7.0.28
-
-### Patch Changes
-
-- Updated dependencies [[`4ecfa0c`](https://github.com/portabletext/editor/commit/4ecfa0cfa97539657b61cf40b3f6d41593f0e7b7)]:
- - @portabletext/editor@7.10.1
-
-## 7.0.27
-
-### Patch Changes
-
-- Updated dependencies [[`067d3e8`](https://github.com/portabletext/editor/commit/067d3e805b7f0b0c01c1e5dbf0c08e800363cf83), [`cbdf301`](https://github.com/portabletext/editor/commit/cbdf3017be649430a7deb0159c1af3a8c83b8704), [`0b82b78`](https://github.com/portabletext/editor/commit/0b82b78ec06c2e000892e1283cdca57fb37d424e), [`f42372f`](https://github.com/portabletext/editor/commit/f42372f1fb8fdacb0b4f250d16a9adaeb9b42574), [`ebff16b`](https://github.com/portabletext/editor/commit/ebff16b56ca7659f806da8b49f75f890e651ff93), [`ebb41dc`](https://github.com/portabletext/editor/commit/ebb41dc0536390f3d1aa2a53bee7ba606306900f), [`2f2d6e9`](https://github.com/portabletext/editor/commit/2f2d6e9ff47c2bc8dad14679939599e26610afaf), [`98f8340`](https://github.com/portabletext/editor/commit/98f83404ec6813b294c09f3ea879a8e7a8792952), [`2831cd9`](https://github.com/portabletext/editor/commit/2831cd9aaa84124bcdb1bd3012bd70a56108f899), [`5dc3030`](https://github.com/portabletext/editor/commit/5dc3030a570710650e838cfcc375e3f0da392b0e), [`f242007`](https://github.com/portabletext/editor/commit/f2420072a74004239502da2413b45d200c1a8022), [`70c90d1`](https://github.com/portabletext/editor/commit/70c90d1db79f3272692012ea99a8e104b736a7f0)]:
- - @portabletext/editor@7.10.0
-
-## 7.0.26
-
-### Patch Changes
-
-- Updated dependencies [[`e8b43db`](https://github.com/portabletext/editor/commit/e8b43db6f14358904a2a328dc17a01f011010ac5), [`50424f9`](https://github.com/portabletext/editor/commit/50424f921d2b6d484cec190b974c28b551ebc1e8), [`24996df`](https://github.com/portabletext/editor/commit/24996df6b0471233a7adeeefbddda4a0965a1ae7)]:
- - @portabletext/editor@7.9.0
-
-## 7.0.25
-
-### Patch Changes
-
-- [#2874](https://github.com/portabletext/editor/pull/2874) [`39f9c40`](https://github.com/portabletext/editor/commit/39f9c406b371ce546df0629f9abc684941245c3c) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency xstate to ^5.32.2
-
-- Updated dependencies [[`1fbedd4`](https://github.com/portabletext/editor/commit/1fbedd4bf013fcb76dbcfb36b3e8d9fa3e163f39), [`e71e642`](https://github.com/portabletext/editor/commit/e71e642956c6b6988416a02ddf71db2dc53a9483), [`ed1845e`](https://github.com/portabletext/editor/commit/ed1845ef9c7075b58596405c62435de14389893e), [`39f9c40`](https://github.com/portabletext/editor/commit/39f9c406b371ce546df0629f9abc684941245c3c), [`cd56b64`](https://github.com/portabletext/editor/commit/cd56b641480a00125d098ff09472394aba631f13), [`46593d5`](https://github.com/portabletext/editor/commit/46593d537ff9d4aa1ef7f3e0ab3333266c749bbb)]:
- - @portabletext/editor@7.8.2
-
-## 7.0.24
-
-### Patch Changes
-
-- Updated dependencies [[`8a84ef6`](https://github.com/portabletext/editor/commit/8a84ef66b97560d00884b63e41cc4d4dd5e90ce4)]:
- - @portabletext/editor@7.8.1
-
-## 7.0.23
-
-### Patch Changes
-
-- [#2845](https://github.com/portabletext/editor/pull/2845) [`6958b15`](https://github.com/portabletext/editor/commit/6958b15f6aba430a65630b2a6aef4db2d6eeb79e) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update react monorepo
-
-- [#2847](https://github.com/portabletext/editor/pull/2847) [`76af976`](https://github.com/portabletext/editor/commit/76af9766fd17334a40b24140e08d114967a31645) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update vitest to ^4.1.9
-
-- Updated dependencies [[`6958b15`](https://github.com/portabletext/editor/commit/6958b15f6aba430a65630b2a6aef4db2d6eeb79e), [`76af976`](https://github.com/portabletext/editor/commit/76af9766fd17334a40b24140e08d114967a31645), [`4c41139`](https://github.com/portabletext/editor/commit/4c41139245fe2e496465a6ef46bbcd70f1ef56c9), [`80c6a80`](https://github.com/portabletext/editor/commit/80c6a8032c0295109c2729b4b9426fc31da59aa5)]:
- - @portabletext/editor@7.8.0
-
-## 7.0.22
-
-### Patch Changes
-
-- Updated dependencies [[`38867cb`](https://github.com/portabletext/editor/commit/38867cb45f3c024cdb402a7caf98511121f88383), [`cdf16f9`](https://github.com/portabletext/editor/commit/cdf16f909eea6fdff36a49265884324e9881eaab), [`b268769`](https://github.com/portabletext/editor/commit/b26876928247ef3357b3c238dc069e569289e555), [`3aa6a39`](https://github.com/portabletext/editor/commit/3aa6a398534e71a01a9c711cbeb474eb815d4fdd)]:
- - @portabletext/editor@7.7.0
-
-## 7.0.21
-
-### Patch Changes
-
-- Updated dependencies [[`29091fe`](https://github.com/portabletext/editor/commit/29091fe7c4d11c5bfc2907d24d921c3a0206bf8a)]:
- - @portabletext/editor@7.6.2
-
-## 7.0.20
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@7.6.1
-
-## 7.0.19
-
-### Patch Changes
-
-- [#2811](https://github.com/portabletext/editor/pull/2811) [`2668d66`](https://github.com/portabletext/editor/commit/2668d66c7eb23bed7e4f5f6ad04ed6753f8a0d68) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): Update xstate to ^5.32.1
-
-- Updated dependencies [[`2668d66`](https://github.com/portabletext/editor/commit/2668d66c7eb23bed7e4f5f6ad04ed6753f8a0d68), [`0768dc5`](https://github.com/portabletext/editor/commit/0768dc5ecff4a5ee90b58242f35a54ac3f6cfbb0), [`737d618`](https://github.com/portabletext/editor/commit/737d618ac78a3ae133701862861f03b9c39a3656)]:
- - @portabletext/editor@7.6.0
-
-## 7.0.18
-
-### Patch Changes
-
-- Updated dependencies [[`c98ddb6`](https://github.com/portabletext/editor/commit/c98ddb6a99829cd6fb14b4b84b65b0857699f0a1)]:
- - @portabletext/editor@7.5.2
-
-## 7.0.17
-
-### Patch Changes
-
-- Updated dependencies [[`68e1f0b`](https://github.com/portabletext/editor/commit/68e1f0b64e59c5923a8cd715cf4fbd59d16f011c)]:
- - @portabletext/editor@7.5.1
-
-## 7.0.16
-
-### Patch Changes
-
-- Updated dependencies [[`5ee8bff`](https://github.com/portabletext/editor/commit/5ee8bffd81826885930b78c35144726fe36b7eb1)]:
- - @portabletext/editor@7.5.0
-
-## 7.0.15
-
-### Patch Changes
-
-- Updated dependencies [[`8ed6233`](https://github.com/portabletext/editor/commit/8ed623380c516add8851fedec26eba62edd13198)]:
- - @portabletext/editor@7.4.0
-
-## 7.0.14
-
-### Patch Changes
-
-- Updated dependencies [[`9173892`](https://github.com/portabletext/editor/commit/91738928cf069ba7b6bf33bb60afea14de678af7)]:
- - @portabletext/editor@7.3.4
-
-## 7.0.13
-
-### Patch Changes
-
-- Updated dependencies [[`1e0d25d`](https://github.com/portabletext/editor/commit/1e0d25d2e909272298c80193f71b604dfde9d7ea)]:
- - @portabletext/editor@7.3.3
-
-## 7.0.12
-
-### Patch Changes
-
-- Updated dependencies [[`c92beef`](https://github.com/portabletext/editor/commit/c92beefeb17631046ea1b5e04c3aa9c4274f520e)]:
- - @portabletext/editor@7.3.2
-
-## 7.0.11
-
-### Patch Changes
-
-- Updated dependencies [[`cfcb9ec`](https://github.com/portabletext/editor/commit/cfcb9ecf2b683bf7c71fb32daa63bbd1935a4d05)]:
- - @portabletext/editor@7.3.1
-
-## 7.0.10
-
-### Patch Changes
-
-- Updated dependencies [[`2b4d9a2`](https://github.com/portabletext/editor/commit/2b4d9a215dfaf2417afec3d9b097776e4637f331)]:
- - @portabletext/editor@7.3.0
-
-## 7.0.9
-
-### Patch Changes
-
-- [#2745](https://github.com/portabletext/editor/pull/2745) [`f4f2a73`](https://github.com/portabletext/editor/commit/f4f2a73666923dba62f0f8e88f87df956fe655b5) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): Update xstate to ^5.32.0
-
-- Updated dependencies [[`e0ee0f6`](https://github.com/portabletext/editor/commit/e0ee0f68ae8936bca7a158c2828c9b17ba468ec2), [`5c183b3`](https://github.com/portabletext/editor/commit/5c183b39b1482d0a83b0b9f98ebe99186560d511), [`f4f2a73`](https://github.com/portabletext/editor/commit/f4f2a73666923dba62f0f8e88f87df956fe655b5), [`3229002`](https://github.com/portabletext/editor/commit/32290029c7e5eed4b8c96833b21181937efcf2a4), [`0fb1f28`](https://github.com/portabletext/editor/commit/0fb1f285fdd54ad9e67a9411829dfa2da283390c), [`ceb179f`](https://github.com/portabletext/editor/commit/ceb179f16e3a218e4e86b05331ab4593d9133602), [`ae60599`](https://github.com/portabletext/editor/commit/ae60599a6eb8514af2c80240f029688dc08bcfc0), [`6540641`](https://github.com/portabletext/editor/commit/65406416e151044913784a11f7a0567e82be48fe), [`492fb7d`](https://github.com/portabletext/editor/commit/492fb7dd390409d4267833ce5f86356a59e38c90)]:
- - @portabletext/editor@7.2.0
-
-## 7.0.8
-
-### Patch Changes
-
-- Updated dependencies [[`4121c36`](https://github.com/portabletext/editor/commit/4121c365871569f7ca0afe54e8400534be54b8e7)]:
- - @portabletext/editor@7.1.1
-
-## 7.0.7
-
-### Patch Changes
-
-- Updated dependencies [[`8ef89bd`](https://github.com/portabletext/editor/commit/8ef89bd074ebcc0484183d69458e5c16bee1398f)]:
- - @portabletext/editor@7.1.0
-
-## 7.0.6
-
-### Patch Changes
-
-- Updated dependencies [[`f0a46d1`](https://github.com/portabletext/editor/commit/f0a46d1362395ff2d10b07c12577212ce5946086)]:
- - @portabletext/editor@7.0.6
-
-## 7.0.5
-
-### Patch Changes
-
-- Updated dependencies [[`e0e974e`](https://github.com/portabletext/editor/commit/e0e974e2ece2590dfd7c7fa908d25290300899fc)]:
- - @portabletext/editor@7.0.5
-
-## 7.0.4
-
-### Patch Changes
-
-- Updated dependencies [[`eb0b234`](https://github.com/portabletext/editor/commit/eb0b234ac1c16ebf89ae0253d02d0845f3d9224d)]:
- - @portabletext/editor@7.0.4
-
-## 7.0.3
-
-### Patch Changes
-
-- Updated dependencies [[`44d5d47`](https://github.com/portabletext/editor/commit/44d5d471ecb95373a7c06d476dd72b5756ad1ba0), [`6ed97e9`](https://github.com/portabletext/editor/commit/6ed97e98b1e6900ad8c48daf7e4c4f265d86bf1d)]:
- - @portabletext/editor@7.0.3
-
-## 7.0.2
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@7.0.2
-
-## 7.0.1
-
-### Patch Changes
-
-- Updated dependencies [[`fdedf2d`](https://github.com/portabletext/editor/commit/fdedf2da4820dc403868fb3027d5945c92ca8a88)]:
- - @portabletext/editor@7.0.1
-
-## 7.0.0
-
-### Patch Changes
-
-- [#2484](https://github.com/portabletext/editor/pull/2484) [`18876ca`](https://github.com/portabletext/editor/commit/18876caecca1f3e7c12d289e53d5665236888caf) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update react monorepo
-
-- [#2658](https://github.com/portabletext/editor/pull/2658) [`d128d51`](https://github.com/portabletext/editor/commit/d128d51e378e62c204ca8d2ed7b24ade6ccdf02a) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency xstate to ^5.31.1
-
-- Updated dependencies [[`ba16137`](https://github.com/portabletext/editor/commit/ba1613704642dbdcc0b596d9195e45c6e9814a11), [`8a91cd2`](https://github.com/portabletext/editor/commit/8a91cd261c27ee2ee5d1be66de55cb32e7cacb6b), [`750f5f4`](https://github.com/portabletext/editor/commit/750f5f49f3c985d55a186ade1ca41e2fa6a1d31e), [`3a3bb24`](https://github.com/portabletext/editor/commit/3a3bb2467fb459fa506744c56f3a62bca78388c5), [`9ee7aed`](https://github.com/portabletext/editor/commit/9ee7aed618a22e34bf28638e9a50ba523b4db8ba), [`63c123d`](https://github.com/portabletext/editor/commit/63c123d533fe97e1f6ad6ceceef44fea60ca7991), [`2053ff7`](https://github.com/portabletext/editor/commit/2053ff75a056f4ff69ae501acc6191c09337c9bc), [`7d1ab61`](https://github.com/portabletext/editor/commit/7d1ab617fbdbd9b6c86d8976af0cf9163f4f6d5f), [`cfdc5c3`](https://github.com/portabletext/editor/commit/cfdc5c397a9091b05678527ac9520bcd262267a0), [`be355f4`](https://github.com/portabletext/editor/commit/be355f49600bb7dd5e01a0b3a88ae6ac21693212), [`7ac3cdc`](https://github.com/portabletext/editor/commit/7ac3cdc1bef5c86c09bbc3320b23e085f71ec0b0), [`3201611`](https://github.com/portabletext/editor/commit/3201611d1af144cdf51f7df72f6783dcf7e034a4), [`4c80f1b`](https://github.com/portabletext/editor/commit/4c80f1b9d0c0e92d93971f64e00a8cca61edc0ea), [`27aff19`](https://github.com/portabletext/editor/commit/27aff19b6d14f49eee24f5d8419e786a972375c4), [`54f47c4`](https://github.com/portabletext/editor/commit/54f47c4661848595119414176787703d097fb23f), [`313428b`](https://github.com/portabletext/editor/commit/313428b35be15cb63681d29ec005593f69508c59), [`7a1fc73`](https://github.com/portabletext/editor/commit/7a1fc738ca907ad479fadc97dca4fcffee766793), [`fe9f223`](https://github.com/portabletext/editor/commit/fe9f2232e3ea549dd1e95e0b481246a54d1fc7be), [`9a36b1e`](https://github.com/portabletext/editor/commit/9a36b1e61a55bb4018d6d2d612cc903a17e109d7), [`18876ca`](https://github.com/portabletext/editor/commit/18876caecca1f3e7c12d289e53d5665236888caf), [`d128d51`](https://github.com/portabletext/editor/commit/d128d51e378e62c204ca8d2ed7b24ade6ccdf02a), [`56edded`](https://github.com/portabletext/editor/commit/56edded088ab9174e1002fc9701929ac6e2900a0), [`84e000f`](https://github.com/portabletext/editor/commit/84e000f7cb272b0b2a35ed85a753e148acff5e7c), [`0715971`](https://github.com/portabletext/editor/commit/07159710b3c7af7b59040a470f5b55ec0c8a8f34), [`1b64415`](https://github.com/portabletext/editor/commit/1b64415cd2a13e3d96aed9f86b8101b2f1907d15), [`345b52b`](https://github.com/portabletext/editor/commit/345b52b73135499575cc8ac3915ed5434989ee76), [`cced43b`](https://github.com/portabletext/editor/commit/cced43bc73c7de85dc7b3a289f5b07d6cf3222be), [`2c6d3a7`](https://github.com/portabletext/editor/commit/2c6d3a7b09bdb04012f6165246a00f71acec1d4a), [`39b0534`](https://github.com/portabletext/editor/commit/39b05340c668e9a1681354bbfdcb60189422851c), [`7ef0f16`](https://github.com/portabletext/editor/commit/7ef0f16f3dd73b327e5b3c75dbc3ae3ffdd4ddac), [`80a648a`](https://github.com/portabletext/editor/commit/80a648a2326a33bc03b0ada49403d0f6419ecd03), [`1206b17`](https://github.com/portabletext/editor/commit/1206b17a66a4611c55ba8b6750db8bdd4efd5c34), [`fc0d815`](https://github.com/portabletext/editor/commit/fc0d8151e909606a499b6c29dd1e46aa48c483cb), [`19fdca2`](https://github.com/portabletext/editor/commit/19fdca2e16c359b6f199196c2fe51abdbd6a24b2), [`c4eb27e`](https://github.com/portabletext/editor/commit/c4eb27e09173b8fa6618107cea5fb7ffd1c2b28f), [`47d6574`](https://github.com/portabletext/editor/commit/47d6574fa215975df6637bf14bead333cf769fa8), [`3d78d55`](https://github.com/portabletext/editor/commit/3d78d55acd9f1771200a4f771f711b235cd287f8), [`703e4a9`](https://github.com/portabletext/editor/commit/703e4a991f540b15ccdfbb0cab3d2d03d9298a0f), [`3a7f607`](https://github.com/portabletext/editor/commit/3a7f60728f8c97d9b31290c86114ed4a8d4b1f48), [`c4bcc8a`](https://github.com/portabletext/editor/commit/c4bcc8a72b4276b74447928936ea83e8d93424aa), [`1e93256`](https://github.com/portabletext/editor/commit/1e93256ca41f2d72cecb992ed2d871b8845c7b2c), [`ff3bc6f`](https://github.com/portabletext/editor/commit/ff3bc6ffef691922eb5656b2f672832789868b7c), [`47d6574`](https://github.com/portabletext/editor/commit/47d6574fa215975df6637bf14bead333cf769fa8), [`d97187d`](https://github.com/portabletext/editor/commit/d97187d4a99524298c1aefacf1330e5b6a2311ed), [`395d017`](https://github.com/portabletext/editor/commit/395d0176f8c82453824699e67770693cf744b6bd), [`8ec6b97`](https://github.com/portabletext/editor/commit/8ec6b973bcb762474aa399c47a2a9f023477331e), [`47d6574`](https://github.com/portabletext/editor/commit/47d6574fa215975df6637bf14bead333cf769fa8), [`f06e37d`](https://github.com/portabletext/editor/commit/f06e37d605aab6e4a5b2f81195528ed21273b487), [`add7f51`](https://github.com/portabletext/editor/commit/add7f5125489fe666aaabe6f79aad90e0f1d598d), [`87ff2dd`](https://github.com/portabletext/editor/commit/87ff2dd2045b33945e5d8a82bbb9b5ae0a345dfb), [`57cd552`](https://github.com/portabletext/editor/commit/57cd552813b3c4a14b47406fc4d8d341eca3ef18), [`b6816f3`](https://github.com/portabletext/editor/commit/b6816f3a595f9ae03c47196e566861c11c5e71ac), [`4daf9bf`](https://github.com/portabletext/editor/commit/4daf9bfe845b15dc9a65dbde0e69937465e9f399), [`a5833da`](https://github.com/portabletext/editor/commit/a5833dac088b9bea6f1de67114c4424bc2634c71), [`aaf491d`](https://github.com/portabletext/editor/commit/aaf491d6b4ffd518f320cad81cb3beaa9f92222c), [`47d6574`](https://github.com/portabletext/editor/commit/47d6574fa215975df6637bf14bead333cf769fa8), [`7d499a0`](https://github.com/portabletext/editor/commit/7d499a035758fbe730457908eab3e4089bc71d37), [`97f9710`](https://github.com/portabletext/editor/commit/97f97102c0249e2ff4c106fedd2a82183768f4f6), [`e365150`](https://github.com/portabletext/editor/commit/e36515014c70337c35ec167a03bed78710632304), [`47d6574`](https://github.com/portabletext/editor/commit/47d6574fa215975df6637bf14bead333cf769fa8), [`57ae20f`](https://github.com/portabletext/editor/commit/57ae20fbc67b4a41cb131b8a0cc22cbb657fd859), [`18c4dcb`](https://github.com/portabletext/editor/commit/18c4dcbed4427aed1f9af4c1545d63e5b6ec6eac), [`3f5f45e`](https://github.com/portabletext/editor/commit/3f5f45e3cc822e87a40edcb56402cb91a9dbe4d9), [`28c2eef`](https://github.com/portabletext/editor/commit/28c2eef89c94af6912194f684899b25717489e7a), [`b7554e0`](https://github.com/portabletext/editor/commit/b7554e00225a4007d81aa9ff070b8f793339de5b), [`47d6574`](https://github.com/portabletext/editor/commit/47d6574fa215975df6637bf14bead333cf769fa8), [`1e7dbd3`](https://github.com/portabletext/editor/commit/1e7dbd3646e9d926b469121c2561e470ab7b31d4), [`1b305c2`](https://github.com/portabletext/editor/commit/1b305c26961eaf40ae8dbe8219188668bbd9d8ea), [`bebcf8b`](https://github.com/portabletext/editor/commit/bebcf8b599e0f8ff73c95b0268c32d768504045f), [`fd73b6e`](https://github.com/portabletext/editor/commit/fd73b6e654fa101273caec75967ddf99cef1f089), [`5b16936`](https://github.com/portabletext/editor/commit/5b16936601b397bd35c645dca1beacf36d4720f6), [`d6e55e3`](https://github.com/portabletext/editor/commit/d6e55e3e71742e20202c5ae68eadb70437857991), [`3a75130`](https://github.com/portabletext/editor/commit/3a751303abb39a12f4f83b9d8fdbd738405a2ee3), [`54138bd`](https://github.com/portabletext/editor/commit/54138bd4295e6a8700cfa5becbb149aa97509452), [`cfd6d48`](https://github.com/portabletext/editor/commit/cfd6d48e9c787844583395966ad27b8c062db1d3), [`6d7f965`](https://github.com/portabletext/editor/commit/6d7f9655019a4b7e225363a012310feec1c33c34)]:
- - @portabletext/editor@7.0.0
-
-## 6.0.25
-
-### Patch Changes
-
-- Updated dependencies [[`2a3e039`](https://github.com/portabletext/editor/commit/2a3e03934d4715b8cb296c3ad81c0a2d104ab449)]:
- - @portabletext/editor@6.6.2
-
-## 6.0.24
-
-### Patch Changes
-
-- [#2452](https://github.com/portabletext/editor/pull/2452) [`550ab67`](https://github.com/portabletext/editor/commit/550ab67d7030a6a2860221877a5c71f8553a58ae) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency xstate to ^5.30.0
-
-- [#2457](https://github.com/portabletext/editor/pull/2457) [`81f6475`](https://github.com/portabletext/editor/commit/81f6475ebc4cbb981169911e34b78f61691f52a5) Thanks [@rexxars](https://github.com/rexxars)! - feat(sdk-value): expose `ValueSyncPlugin`
-
-- Updated dependencies [[`1f14d95`](https://github.com/portabletext/editor/commit/1f14d9503d129d96554b04efce3bf11c6175fd4e), [`1883b7c`](https://github.com/portabletext/editor/commit/1883b7ccfc197d8f40ca965d4a5c8d5875001846), [`550ab67`](https://github.com/portabletext/editor/commit/550ab67d7030a6a2860221877a5c71f8553a58ae), [`ef6daba`](https://github.com/portabletext/editor/commit/ef6dabae69e60abe6c3a35f9716f63fc53b1f73c), [`388ccd3`](https://github.com/portabletext/editor/commit/388ccd39a4d63df1dda2cc99aea741d0a98510ed), [`b849bc7`](https://github.com/portabletext/editor/commit/b849bc7120815fd8e3c9b8874371a6f34d21e374), [`69d82a3`](https://github.com/portabletext/editor/commit/69d82a3e34653b4b12f72a954f3d2e580838ccb2), [`0250fe0`](https://github.com/portabletext/editor/commit/0250fe0e6ff6f29e52fc15ceaa3e295c33430003), [`6334c3a`](https://github.com/portabletext/editor/commit/6334c3a8b616cccc21f2be899b3d887af9442bd4), [`9ac3212`](https://github.com/portabletext/editor/commit/9ac3212c6d7e3c14461c3c5adef9254f69afa4c2), [`995adc6`](https://github.com/portabletext/editor/commit/995adc68d3351332c6c1f2bb82432a5e85bc6d38), [`0464f65`](https://github.com/portabletext/editor/commit/0464f65bb76403b1bce7cfaeaa4ceb09b6596e50)]:
- - @portabletext/editor@6.6.1
-
-## 6.0.23
-
-### Patch Changes
-
-- Updated dependencies [[`ff8220d`](https://github.com/portabletext/editor/commit/ff8220db49b8407664b06d840f3d20b393b0effd), [`f1a6fb4`](https://github.com/portabletext/editor/commit/f1a6fb46291d862f385ebb0ecdacc712feed8d52), [`a8bdabb`](https://github.com/portabletext/editor/commit/a8bdabbb644bec953a29a52b4241a5d279399246), [`b97146c`](https://github.com/portabletext/editor/commit/b97146ccf45cc6d51dbd6b4d0d86015fa2af8039), [`4247d17`](https://github.com/portabletext/editor/commit/4247d174801ffac782906a4569de3536dd7e2079), [`055bdb1`](https://github.com/portabletext/editor/commit/055bdb160eb0b4e83e291ac3bf508ed6865747b8), [`041fef0`](https://github.com/portabletext/editor/commit/041fef01c7663317e7e13fc9197536c23822709f), [`56c20c3`](https://github.com/portabletext/editor/commit/56c20c34a7378e141126d5e63aded6e3b4d810da), [`d1928a2`](https://github.com/portabletext/editor/commit/d1928a2661ef5319f3bf7602b03bf650f726f3f2)]:
- - @portabletext/editor@6.6.0
-
-## 6.0.22
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@6.5.2
-
-## 6.0.21
-
-### Patch Changes
-
-- Updated dependencies [[`746bad3`](https://github.com/portabletext/editor/commit/746bad3e3199fa15cdd87c08396f120c01f4a3e8), [`182af30`](https://github.com/portabletext/editor/commit/182af3025562c832d553c11badea49cd18665ad2)]:
- - @portabletext/editor@6.5.1
-
-## 6.0.20
-
-### Patch Changes
-
-- Updated dependencies [[`cbccc01`](https://github.com/portabletext/editor/commit/cbccc0178f0eab4732424a579411a7e711786266), [`3d026ee`](https://github.com/portabletext/editor/commit/3d026ee624e62970429199b9082b7a3bab7e26db), [`a1992ab`](https://github.com/portabletext/editor/commit/a1992abed6f2a38486c9c9734949f0cc2ae97396), [`d93fd9b`](https://github.com/portabletext/editor/commit/d93fd9b17fc1bbae0c70fe323537563e81944238), [`4e86fc3`](https://github.com/portabletext/editor/commit/4e86fc34824fe5e2c6eb78e6277475702f434c99)]:
- - @portabletext/editor@6.5.0
-
-## 6.0.19
-
-### Patch Changes
-
-- Updated dependencies [[`e6815f7`](https://github.com/portabletext/editor/commit/e6815f794bbf282ad434b42992181db8c27eaa0c), [`71f1d38`](https://github.com/portabletext/editor/commit/71f1d38465a8c5b4e4c79116dbb9c105855e48b6), [`a698b0a`](https://github.com/portabletext/editor/commit/a698b0ae35f690ce31d4410d47e16698b1998cf4), [`c512b8b`](https://github.com/portabletext/editor/commit/c512b8bf4bd091afccedd535d93ebad9f383bacf), [`61abd09`](https://github.com/portabletext/editor/commit/61abd09b56e76de97bc0617bc824087f4e5457a9), [`014c3b4`](https://github.com/portabletext/editor/commit/014c3b4656efcc75f81c3a27fc9a637cab91f12c), [`19eb009`](https://github.com/portabletext/editor/commit/19eb009158853dae411e9f2bcd700381a1b62f9a), [`9299613`](https://github.com/portabletext/editor/commit/9299613d8876cdd60c31fb0b71c3c84cb2548c6c), [`1d7b52e`](https://github.com/portabletext/editor/commit/1d7b52e7c86486545514b33bb9dee54efeeb266c)]:
- - @portabletext/editor@6.4.0
-
-## 6.0.18
-
-### Patch Changes
-
-- Updated dependencies [[`b245c6e`](https://github.com/portabletext/editor/commit/b245c6e3b9dea50e3eab1f475df85d68bd4d0f94), [`dba286d`](https://github.com/portabletext/editor/commit/dba286de99fe63debc543fc354713dcf0b1fd0bf), [`6e7ef87`](https://github.com/portabletext/editor/commit/6e7ef8735a7e4ce66866cc54ef8d21f8350ef1d6), [`75dcbad`](https://github.com/portabletext/editor/commit/75dcbad57e7a220a9d8c0cb4d1581037a7134bab), [`d5d8fc9`](https://github.com/portabletext/editor/commit/d5d8fc98ad4b8482e6724644bdfe4dcac2f71d5c), [`a02e017`](https://github.com/portabletext/editor/commit/a02e017bf09a071caceea4648deee9becb311408), [`d4068ce`](https://github.com/portabletext/editor/commit/d4068ceb273aec29a789c76d8706ce8e00ad9138), [`b89f7f2`](https://github.com/portabletext/editor/commit/b89f7f2b35893004afd77ceb27de4def9a8279ef), [`a657b0d`](https://github.com/portabletext/editor/commit/a657b0d6c1061f13ec9c8c6229ff10201dc525a5), [`e6b2825`](https://github.com/portabletext/editor/commit/e6b28255d13404ace2ea12193d432f9a7da96748)]:
- - @portabletext/editor@6.3.2
-
-## 6.0.17
-
-### Patch Changes
-
-- Updated dependencies [[`262b0bc`](https://github.com/portabletext/editor/commit/262b0bc01b35491b82700e63c5a98d6ddc4d9513), [`d992e30`](https://github.com/portabletext/editor/commit/d992e30c5d91876ae43b0d5d82caee3c48259595), [`f06602e`](https://github.com/portabletext/editor/commit/f06602ea0e2d288c306230358e37e9fa8e7a9f5d), [`6a6ef2b`](https://github.com/portabletext/editor/commit/6a6ef2be1aa039de899a845f3a79f3e9958f51bc)]:
- - @portabletext/editor@6.3.1
-
-## 6.0.16
-
-### Patch Changes
-
-- Updated dependencies [[`58d4eb1`](https://github.com/portabletext/editor/commit/58d4eb11bf2f069acd10c4ef8ae2c1e87b57f75c), [`eb3c4ce`](https://github.com/portabletext/editor/commit/eb3c4cef6f14d5ec7fa0325e5f19c6191524d44c)]:
- - @portabletext/editor@6.3.0
-
-## 6.0.15
-
-### Patch Changes
-
-- Updated dependencies [[`d312abd`](https://github.com/portabletext/editor/commit/d312abd5b07affa20b5defb2fe587a66394e0831)]:
- - @portabletext/editor@6.2.0
-
-## 6.0.14
-
-### Patch Changes
-
-- Updated dependencies [[`761233d`](https://github.com/portabletext/editor/commit/761233d7dc3493eebfb7fe8e0f841a382105b543)]:
- - @portabletext/editor@6.1.2
-
-## 6.0.13
-
-### Patch Changes
-
-- Updated dependencies [[`626a8c4`](https://github.com/portabletext/editor/commit/626a8c4bfb0f739c3bdf1b4df3db42a38fd4ac90)]:
- - @portabletext/editor@6.1.1
-
-## 6.0.12
-
-### Patch Changes
-
-- Updated dependencies [[`a7cc971`](https://github.com/portabletext/editor/commit/a7cc9717e2438fcb461c7119136234f691fb9bbb), [`da1e5ff`](https://github.com/portabletext/editor/commit/da1e5ffd3a82f350aa4b6d30b21972d18cc16abd), [`67089e4`](https://github.com/portabletext/editor/commit/67089e4a9b38cb5711f050c47d0fb029a9d1a828), [`1eb5078`](https://github.com/portabletext/editor/commit/1eb50782640e274fa085f8032d8643b0791198e0), [`94ed1ea`](https://github.com/portabletext/editor/commit/94ed1ea6c4bd8d19fba2ac79abc95b5f5e756750), [`919c976`](https://github.com/portabletext/editor/commit/919c97670fd1446dea189792639ea90d6a43cee0), [`d1692de`](https://github.com/portabletext/editor/commit/d1692de11f086fd7e95f0799de295922b2244cf7), [`e939322`](https://github.com/portabletext/editor/commit/e939322b1e087a6f927b4d6f82b9b02154c181b4), [`82b41bf`](https://github.com/portabletext/editor/commit/82b41bf170355f24c4db501567b51bd89c8a71fc), [`92aafc5`](https://github.com/portabletext/editor/commit/92aafc59990627a56aff431214fecaffc60b9d96)]:
- - @portabletext/editor@6.1.0
-
-## 6.0.11
-
-### Patch Changes
-
-- Updated dependencies [[`4f31f06`](https://github.com/portabletext/editor/commit/4f31f06917b216f25cff8a04a204e15a6750ab91)]:
- - @portabletext/editor@6.0.11
-
-## 6.0.10
-
-### Patch Changes
-
-- Updated dependencies [[`eec5bfa`](https://github.com/portabletext/editor/commit/eec5bfab7d50cc25a9de27bf6f21a586701a8650)]:
- - @portabletext/editor@6.0.10
-
-## 6.0.9
-
-### Patch Changes
-
-- Updated dependencies [[`3149548`](https://github.com/portabletext/editor/commit/314954827b7c1df1d10b581dfe33c7ad175030ca), [`55ceaf2`](https://github.com/portabletext/editor/commit/55ceaf258948ad1dc9a2e41086821095f730ca25)]:
- - @portabletext/editor@6.0.9
-
-## 6.0.8
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@6.0.8
-
-## 6.0.7
-
-### Patch Changes
-
-- Updated dependencies [[`ef4fe18`](https://github.com/portabletext/editor/commit/ef4fe182bec3696d3b4588c7c44e4ed9c3f680fd)]:
- - @portabletext/editor@6.0.7
-
-## 6.0.6
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@6.0.6
-
-## 6.0.5
-
-### Patch Changes
-
-- Updated dependencies [[`c90dd12`](https://github.com/portabletext/editor/commit/c90dd12039ddb2502f740a5e84ece54b32ea2008)]:
- - @portabletext/editor@6.0.5
-
-## 6.0.4
-
-### Patch Changes
-
-- [#2292](https://github.com/portabletext/editor/pull/2292) [`e71f420`](https://github.com/portabletext/editor/commit/e71f420de68de7d99eaacee405c8eeaa7f983c35) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): Update xstate
-
-- Updated dependencies [[`e71f420`](https://github.com/portabletext/editor/commit/e71f420de68de7d99eaacee405c8eeaa7f983c35)]:
- - @portabletext/editor@6.0.4
-
-## 6.0.3
-
-### Patch Changes
-
-- Updated dependencies [[`08d7e56`](https://github.com/portabletext/editor/commit/08d7e56e0623ddfde4af4f827af09f19deabe44d), [`bfa7feb`](https://github.com/portabletext/editor/commit/bfa7feb46aca3e9ef5fcd8f35a87177a2f75816d)]:
- - @portabletext/editor@6.0.3
-
-## 6.0.2
-
-### Patch Changes
-
-- Updated dependencies [[`68d4f82`](https://github.com/portabletext/editor/commit/68d4f82bf596724d8bed31721786f21f5dea3377)]:
- - @portabletext/editor@6.0.2
-
-## 6.0.1
-
-### Patch Changes
-
-- Updated dependencies [[`da6e04f`](https://github.com/portabletext/editor/commit/da6e04f3685de0ecab1bee38c941d5cdd3cd1aac), [`a4b0b48`](https://github.com/portabletext/editor/commit/a4b0b484e865a83174d27196112c619ffd9b1605), [`9e768b1`](https://github.com/portabletext/editor/commit/9e768b1d88446d89bbfc9dd7d0e54ba3d7d09765), [`d28c017`](https://github.com/portabletext/editor/commit/d28c017bec5a064cd3402b9a99a3358f693c4238), [`c3b7905`](https://github.com/portabletext/editor/commit/c3b79057c4992409dde5646d86d3b7c5d3db26a3), [`e9bcda3`](https://github.com/portabletext/editor/commit/e9bcda385fb8217fddffe039325a9d338a51adec), [`80c7378`](https://github.com/portabletext/editor/commit/80c73781a0d45fce376083a810f16b1438c9d94f), [`77a10ce`](https://github.com/portabletext/editor/commit/77a10ced03fe211bd912b520e7fb469985fec1af), [`018857f`](https://github.com/portabletext/editor/commit/018857fc34d9d600d4a45c06b1b62926759e4164), [`398adef`](https://github.com/portabletext/editor/commit/398adefc035c177dafd0b16d7dbdcd8de6f86fde), [`7d5b051`](https://github.com/portabletext/editor/commit/7d5b051a4a310b798b62ba78b6fea0a11351ed48)]:
- - @portabletext/editor@6.0.1
-
-## 6.0.0
-
-### Patch Changes
-
-- Updated dependencies [[`79b69a5`](https://github.com/portabletext/editor/commit/79b69a5cd7f5a19d4393453b993611916ab86a95), [`5a3e8bf`](https://github.com/portabletext/editor/commit/5a3e8bf33d9591b9cfbf310e37ae95f736862942), [`2f8d366`](https://github.com/portabletext/editor/commit/2f8d36694ddad97a5b1ca910ffc7f7e60937c642), [`3ce0561`](https://github.com/portabletext/editor/commit/3ce056153812bf75c3d95a452417f1f7e45f352e)]:
- - @portabletext/editor@6.0.0
-
-## 5.0.8
-
-### Patch Changes
-
-- Updated dependencies [[`837aab4`](https://github.com/portabletext/editor/commit/837aab4fa86dd32b4cf59b81a0a1ee53aab525aa)]:
- - @portabletext/editor@5.1.1
-
-## 5.0.7
-
-### Patch Changes
-
-- Updated dependencies [[`9840585`](https://github.com/portabletext/editor/commit/9840585b286929ff095cd2ebf3b1ead8b47a0edf)]:
- - @portabletext/editor@5.1.0
-
-## 5.0.6
-
-### Patch Changes
-
-- [#2232](https://github.com/portabletext/editor/pull/2232) [`438b860`](https://github.com/portabletext/editor/commit/438b860db51dcd76b33e6710cd13530a119931ab) Thanks [@christianhg](https://github.com/christianhg)! - fix: replace boolean flags with XState machine
-
- The plugin used boolean flags (`isLocalWrite`, `hasPendingWrites`, `pendingSync`) to coordinate sync between the editor and the SDK store. These flags were fragile: the `useEffect` that managed them re-ran whenever `setSdkValue` changed reference (every parent render), sending stale update value events that caused data loss during rapid typing.
-
-## 5.0.5
-
-### Patch Changes
-
-- [#2227](https://github.com/portabletext/editor/pull/2227) [`687bbbf`](https://github.com/portabletext/editor/commit/687bbbf3d49731de0db755bc5d88d0892fca7bc6) Thanks [@christianhg](https://github.com/christianhg)! - Fix `useEffect` dependency array in `SDKValuePlugin` — destructure `props` into primitive values (`documentId`, `documentType`, `path`) to prevent subscriptions from being torn down and re-created on every parent re-render.
-
-- [#2220](https://github.com/portabletext/editor/pull/2220) [`a5875fe`](https://github.com/portabletext/editor/commit/a5875feeacbee46ca3227c72f36a4524bee5acfc) Thanks [@christianhg](https://github.com/christianhg)! - fix: defer SDK sync when editor has pending writes
-
-## 5.0.4
-
-### Patch Changes
-
-- [#2209](https://github.com/portabletext/editor/pull/2209) [`f5dc492`](https://github.com/portabletext/editor/commit/f5dc49272e293ec94511d49ed76d995863d58dba) Thanks [@christianhg](https://github.com/christianhg)! - fix: suppress echo callback on local writes in SDKValuePlugin
-
- Add a local-write flag to prevent the SDK change subscriber from
- sending spurious patches back to the editor after a local edit.
- The entire chain from setSdkValue to onSdkValueChange is synchronous,
- so the flag reliably distinguishes local writes from remote changes.
-
-- [#2209](https://github.com/portabletext/editor/pull/2209) [`600f87a`](https://github.com/portabletext/editor/commit/600f87a17666a06468454552c824531cbcd1972c) Thanks [@christianhg](https://github.com/christianhg)! - fix: switch SDKValuePlugin from patch to mutation event
-
- Switch from `editor.on('patch')` to `editor.on('mutation')` to reduce
- SDK store updates from N-per-keystroke to 1-per-action. The mutation
- event batches patches by operation and debounces during typing (250ms).
- It also includes the editor value, avoiding an extra snapshot read.
-
-- Updated dependencies [[`a3eb985`](https://github.com/portabletext/editor/commit/a3eb985d2fe074ac5a62b53acc50d9f4f1cbddcb)]:
- - @portabletext/editor@5.0.4
-
-## 5.0.3
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@5.0.3
-
-## 5.0.2
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@5.0.2
-
-## 5.0.1
-
-### Patch Changes
-
-- Updated dependencies [[`0155283`](https://github.com/portabletext/editor/commit/0155283c5b398f5678222acfdf7da7229a6fe0a6), [`921d03c`](https://github.com/portabletext/editor/commit/921d03c3d42b80949b25940d85cbc913dcc91f18)]:
- - @portabletext/editor@5.0.1
-
-## 5.0.0
-
-### Patch Changes
-
-- Updated dependencies [[`aadc179`](https://github.com/portabletext/editor/commit/aadc179d1a1181fb52af5905d9be9360b804ab81)]:
- - @portabletext/editor@5.0.0
-
-## 4.0.25
-
-### Patch Changes
-
-- Updated dependencies [[`3900875`](https://github.com/portabletext/editor/commit/3900875d6cefc6b66e0b0282eda1216ae8ede67c)]:
- - @portabletext/editor@4.3.10
-
-## 4.0.24
-
-### Patch Changes
-
-- Updated dependencies [[`b700377`](https://github.com/portabletext/editor/commit/b7003778bfff174842f264c392d4bb7641e02001)]:
- - @portabletext/editor@4.3.9
-
-## 4.0.23
-
-### Patch Changes
-
-- Updated dependencies [[`9e5cab1`](https://github.com/portabletext/editor/commit/9e5cab1d73b1bdfa011bc69654d1476a42a2fd94)]:
- - @portabletext/editor@4.3.8
-
-## 4.0.22
-
-### Patch Changes
-
-- Updated dependencies [[`ed5e0a0`](https://github.com/portabletext/editor/commit/ed5e0a06523ff4a46579156e0093c778f0478f94)]:
- - @portabletext/editor@4.3.7
-
-## 4.0.21
-
-### Patch Changes
-
-- Updated dependencies [[`30f57d3`](https://github.com/portabletext/editor/commit/30f57d39b902eb2022d96f42bf8a935bdc6b9c6d)]:
- - @portabletext/editor@4.3.6
-
-## 4.0.20
-
-### Patch Changes
-
-- Updated dependencies [[`ddb324f`](https://github.com/portabletext/editor/commit/ddb324f3294ed961092ad580d69c6c629f6a47d1), [`39b8b21`](https://github.com/portabletext/editor/commit/39b8b21dea18651d8c7e306ea6953b95d9648bb8)]:
- - @portabletext/editor@4.3.5
-
-## 4.0.19
-
-### Patch Changes
-
-- Updated dependencies [[`644f895`](https://github.com/portabletext/editor/commit/644f8957344bb62c017d86505795281a9f5f54f4), [`78dfe5e`](https://github.com/portabletext/editor/commit/78dfe5ee8a485b75bd9bc38dc3c023cf9bda7da8)]:
- - @portabletext/editor@4.3.4
-
-## 4.0.18
-
-### Patch Changes
-
-- Updated dependencies [[`c98cbb8`](https://github.com/portabletext/editor/commit/c98cbb806f0887e98a38b5bdfeb2d6f44d9ccc60)]:
- - @portabletext/editor@4.3.3
-
-## 4.0.17
-
-### Patch Changes
-
-- Updated dependencies [[`cdd34ea`](https://github.com/portabletext/editor/commit/cdd34eae96da4fdcc3b6c3272e0e89b88c410252)]:
- - @portabletext/editor@4.3.2
-
-## 4.0.16
-
-### Patch Changes
-
-- Updated dependencies [[`427ccce`](https://github.com/portabletext/editor/commit/427cccef816c9b6af520123bfeb56b91738a7012)]:
- - @portabletext/editor@4.3.1
-
-## 4.0.15
-
-### Patch Changes
-
-- Updated dependencies [[`dd5e621`](https://github.com/portabletext/editor/commit/dd5e621856680b6eacb36903200413e2e27b57e3), [`ff20d55`](https://github.com/portabletext/editor/commit/ff20d55c80a913769f620a0ae0537e934a0b3219)]:
- - @portabletext/editor@4.3.0
-
-## 4.0.14
-
-### Patch Changes
-
-- Updated dependencies [[`72e96e8`](https://github.com/portabletext/editor/commit/72e96e88579a88ccf7fdab141653a529c8f6e44b)]:
- - @portabletext/editor@4.2.4
-
-## 4.0.13
-
-### Patch Changes
-
-- Updated dependencies [[`d6a04e8`](https://github.com/portabletext/editor/commit/d6a04e8328e8410220391c9bf56b8f2a969a20ab), [`6d7adef`](https://github.com/portabletext/editor/commit/6d7adef5c716b279fa1f35454c537cf9c79502e2)]:
- - @portabletext/editor@4.2.3
-
-## 4.0.12
-
-### Patch Changes
-
-- Updated dependencies [[`bdf8fa8`](https://github.com/portabletext/editor/commit/bdf8fa833c50e54c2e422752d4c852eaae486b49), [`dc06360`](https://github.com/portabletext/editor/commit/dc063604ed3ab7e769da61e9c784cef92bf5b4bc), [`89c0f59`](https://github.com/portabletext/editor/commit/89c0f59603c05514fe64f5972caf92ae163c2b75), [`f65f991`](https://github.com/portabletext/editor/commit/f65f99124cac3b7cdbfd7ec594218b5f6bbaa940), [`cdaab46`](https://github.com/portabletext/editor/commit/cdaab461425787405946ad1be608972471802fe0)]:
- - @portabletext/editor@4.2.2
-
-## 4.0.11
-
-### Patch Changes
-
-- Updated dependencies [[`fbffddf`](https://github.com/portabletext/editor/commit/fbffddfea67f3a8ab79d5619b54f58a54898d8ac), [`2e9feaf`](https://github.com/portabletext/editor/commit/2e9feafc563905cad14b108b70446d11ef297909), [`6695425`](https://github.com/portabletext/editor/commit/6695425d4bc11f41c355fc0b01d82917e4c57051)]:
- - @portabletext/editor@4.2.1
-
-## 4.0.10
-
-### Patch Changes
-
-- Updated dependencies [[`eb23bfe`](https://github.com/portabletext/editor/commit/eb23bfed827103450317516f46b022b741207f3e), [`d4d7c11`](https://github.com/portabletext/editor/commit/d4d7c11bd4c765438ce3e92e0e9d91efc61adce0), [`2aaf043`](https://github.com/portabletext/editor/commit/2aaf0438c04266b4f1c565c04eae175adf4d30b0), [`2209a45`](https://github.com/portabletext/editor/commit/2209a45ed7dce684f7460537d3663ef3a7201c09), [`7787d93`](https://github.com/portabletext/editor/commit/7787d9334792c100e234320209b0fa654c356958), [`f677a35`](https://github.com/portabletext/editor/commit/f677a35debb33491ae32f07456fa859bd6233871)]:
- - @portabletext/editor@4.2.0
-
-## 4.0.9
-
-### Patch Changes
-
-- Updated dependencies [[`6e5f39e`](https://github.com/portabletext/editor/commit/6e5f39e7a4104298feaadf0a05fc41424adf8b24), [`ee2f480`](https://github.com/portabletext/editor/commit/ee2f480c4f0d162dc5c590c6f5a2665864a40d6e)]:
- - @portabletext/editor@4.1.5
-
-## 4.0.8
-
-### Patch Changes
-
-- Updated dependencies [[`cbad0f7`](https://github.com/portabletext/editor/commit/cbad0f7b9500fc2eddedd122d1be3256b2cbeb89)]:
- - @portabletext/editor@4.1.4
-
-## 4.0.7
-
-### Patch Changes
-
-- Updated dependencies [[`793c8a0`](https://github.com/portabletext/editor/commit/793c8a0a0ca99eb79e2e99ec3da44bd4a5e219c5), [`56587f5`](https://github.com/portabletext/editor/commit/56587f5a2645bd1238de743946f2661ba199b744)]:
- - @portabletext/editor@4.1.3
-
-## 4.0.6
-
-### Patch Changes
-
-- Updated dependencies [[`25806bb`](https://github.com/portabletext/editor/commit/25806bbb09d7327aca59efad85d5fa9a2a965ce4), [`f082dd1`](https://github.com/portabletext/editor/commit/f082dd1945758a5099901acf5ed91dd9906864dc), [`c486169`](https://github.com/portabletext/editor/commit/c4861691bf018a4e87ebdf059a50baaeb5a9a484), [`a880f48`](https://github.com/portabletext/editor/commit/a880f48ab2aa340c88b9eadc5bc1b3a3d86745c8)]:
- - @portabletext/editor@4.1.2
-
-## 4.0.5
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@4.1.1
-
-## 4.0.4
-
-### Patch Changes
-
-- Updated dependencies [[`df0f265`](https://github.com/portabletext/editor/commit/df0f26503be65074377603bcb5e2ee079fddab42), [`9e49556`](https://github.com/portabletext/editor/commit/9e495566240c73534bfc80ed93926314292eb5d4)]:
- - @portabletext/editor@4.1.0
-
-## 4.0.3
-
-### Patch Changes
-
-- Updated dependencies [[`563bd6a`](https://github.com/portabletext/editor/commit/563bd6a109055428060498dc5bd7f8b39141f482)]:
- - @portabletext/editor@4.0.3
-
-## 4.0.2
-
-### Patch Changes
-
-- Updated dependencies [[`82732ce`](https://github.com/portabletext/editor/commit/82732ce54dfff42e13458e13697caeb21f36fcbd), [`58ea2a8`](https://github.com/portabletext/editor/commit/58ea2a84b481dd473ca2762d2c19efb2008e3bba), [`8db1e94`](https://github.com/portabletext/editor/commit/8db1e947bb331c056f8501ae666c9b6edb9f8f9c), [`a399271`](https://github.com/portabletext/editor/commit/a399271da57164c5c160720c071544af71c7061a), [`4e5d9df`](https://github.com/portabletext/editor/commit/4e5d9df31b7ad7043178069b9f1d3a02e526d4bd), [`d3ee31d`](https://github.com/portabletext/editor/commit/d3ee31d38ac86be91cef8156ad9e7eaaac33aa72), [`b575621`](https://github.com/portabletext/editor/commit/b575621ae5f4c528816e25f00c192b2b24b1e8a6)]:
- - @portabletext/editor@4.0.2
-
-## 4.0.1
-
-### Patch Changes
-
-- Updated dependencies [[`2f801bd`](https://github.com/portabletext/editor/commit/2f801bd608ef9d69f93c5e0906d28d8c8c59f10b)]:
- - @portabletext/editor@4.0.1
-
-## 4.0.0
-
-### Major Changes
-
-- [#2043](https://github.com/portabletext/editor/pull/2043) [`6af9559`](https://github.com/portabletext/editor/commit/6af9559d273b85113d9eba92ca85d6322a581764) Thanks [@stipsan](https://github.com/stipsan)! - Require React 19.2 or later
-
-- [#2043](https://github.com/portabletext/editor/pull/2043) [`6af9559`](https://github.com/portabletext/editor/commit/6af9559d273b85113d9eba92ca85d6322a581764) Thanks [@stipsan](https://github.com/stipsan)! - Require v5 of sanity studio dependencies
-
-### Patch Changes
-
-- Updated dependencies [[`bfd5fad`](https://github.com/portabletext/editor/commit/bfd5fad25679bfc553c7c45779940d227a177813), [`6af9559`](https://github.com/portabletext/editor/commit/6af9559d273b85113d9eba92ca85d6322a581764), [`6af9559`](https://github.com/portabletext/editor/commit/6af9559d273b85113d9eba92ca85d6322a581764)]:
- - @portabletext/editor@4.0.0
-
-## 3.0.36
-
-### Patch Changes
-
-- Updated dependencies [[`c70001b`](https://github.com/portabletext/editor/commit/c70001ba2db6183e2ed43afcc6632a78d6f009b4)]:
- - @portabletext/editor@3.3.16
-
-## 3.0.35
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@3.3.15
-
-## 3.0.34
-
-### Patch Changes
-
-- Updated dependencies [[`1dde866`](https://github.com/portabletext/editor/commit/1dde8666e528f934c7f1a1c6fe3ed94e1927b306), [`2f411d3`](https://github.com/portabletext/editor/commit/2f411d309dadc379e0cc08c6a7f9eaae2ceba950), [`80d9a45`](https://github.com/portabletext/editor/commit/80d9a45e0c7ee5549dae92162113c888df57e01c), [`6c358bd`](https://github.com/portabletext/editor/commit/6c358bde844b2cd47cf4eac44de53eb984a787a4), [`61620f4`](https://github.com/portabletext/editor/commit/61620f483098c035167b54cdef6bcddbc1eacf4d)]:
- - @portabletext/editor@3.3.14
-
-## 3.0.33
-
-### Patch Changes
-
-- [#2027](https://github.com/portabletext/editor/pull/2027) [`f61c9d2`](https://github.com/portabletext/editor/commit/f61c9d2f24bf8cb4cf313dfe762b192bd68bf11b) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update react monorepo to ^19.2.3
-
-- Updated dependencies [[`f61c9d2`](https://github.com/portabletext/editor/commit/f61c9d2f24bf8cb4cf313dfe762b192bd68bf11b), [`23ed760`](https://github.com/portabletext/editor/commit/23ed76034c5b7ceada84f6dd5ad7193e5f611136)]:
- - @portabletext/editor@3.3.13
-
-## 3.0.32
-
-### Patch Changes
-
-- Updated dependencies [[`f2ea700`](https://github.com/portabletext/editor/commit/f2ea700de5e4a3d2129a3c81d0add089d0248ef3), [`944eb12`](https://github.com/portabletext/editor/commit/944eb12c5994e0ecefcf17d546067beee8a586db), [`61b1135`](https://github.com/portabletext/editor/commit/61b1135e43c960fcc892c9523d62b2eb73b6bd00)]:
- - @portabletext/editor@3.3.12
-
-## 3.0.31
-
-### Patch Changes
-
-- Updated dependencies []:
- - @portabletext/editor@3.3.11
-
-## 3.0.30
-
-### Patch Changes
-
-- Updated dependencies [[`8774227`](https://github.com/portabletext/editor/commit/8774227099edf58ac73894a159961528ff68ec95)]:
- - @portabletext/editor@3.3.10
-
-## 3.0.29
-
-### Patch Changes
-
-- Updated dependencies [[`0e45606`](https://github.com/portabletext/editor/commit/0e4560697a88b9d39fbfb5ad3340df62d97f1042), [`5a7ae86`](https://github.com/portabletext/editor/commit/5a7ae8626920ba36bb731d6605a1f068a3c2f325)]:
- - @portabletext/editor@3.3.9
-
-## 3.0.28
-
-### Patch Changes
-
-- Updated dependencies [[`38b9bba`](https://github.com/portabletext/editor/commit/38b9bba925598e5444abb47a8bf20f1a2e625cc7)]:
- - @portabletext/editor@3.3.8
-
-## 3.0.27
-
-### Patch Changes
-
-- Updated dependencies [[`4931b87`](https://github.com/portabletext/editor/commit/4931b87a595b0876db72e5e58650af5047d58754)]:
- - @portabletext/editor@3.3.7
-
-## 3.0.26
-
-### Patch Changes
-
-- Updated dependencies [[`77aa97a`](https://github.com/portabletext/editor/commit/77aa97a7c5901557c162be52ea3d48c3ff9105ce), [`cf0572b`](https://github.com/portabletext/editor/commit/cf0572b93b5179b74239418a6df671530a4cf865)]:
- - @portabletext/editor@3.3.6
-
-## 3.0.25
-
-### Patch Changes
-
-- Updated dependencies [[`7ddb2c8`](https://github.com/portabletext/editor/commit/7ddb2c83b8421cc62bf6e8398ff965621db2e541)]:
- - @portabletext/editor@3.3.5
-
-## 3.0.24
-
-### Patch Changes
-
-- [#1984](https://github.com/portabletext/editor/pull/1984) [`56168e5`](https://github.com/portabletext/editor/commit/56168e5a84f38bbb1ab9f2d85c8d5745b15e22da) Thanks [@stipsan](https://github.com/stipsan)! - Stop publishing src folder to npm
-
-- Updated dependencies [[`56168e5`](https://github.com/portabletext/editor/commit/56168e5a84f38bbb1ab9f2d85c8d5745b15e22da)]:
- - @portabletext/editor@3.3.4
-
-## 3.0.23
-
-### Patch Changes
-
-- [#1981](https://github.com/portabletext/editor/pull/1981) [`23e9930`](https://github.com/portabletext/editor/commit/23e993070ead298cde133970746cb41f3fa571d6) Thanks [@stipsan](https://github.com/stipsan)! - Use relative `^` semver for react compiler deps
-
-- Updated dependencies [[`23e9930`](https://github.com/portabletext/editor/commit/23e993070ead298cde133970746cb41f3fa571d6), [`23e9930`](https://github.com/portabletext/editor/commit/23e993070ead298cde133970746cb41f3fa571d6), [`c3c41b1`](https://github.com/portabletext/editor/commit/c3c41b1f6f468b87a1040fdc3f2eac2e7a618dde), [`23e9930`](https://github.com/portabletext/editor/commit/23e993070ead298cde133970746cb41f3fa571d6)]:
- - @portabletext/editor@3.3.3
-
-## 3.0.22
-
-### Patch Changes
-
-- Updated dependencies [[`41320f7`](https://github.com/portabletext/editor/commit/41320f74b08c0be78a1de7ddb59e1c84cc09e0b9), [`83c6c09`](https://github.com/portabletext/editor/commit/83c6c098d0dfc06d37b7dae0a4164e1487316586)]:
- - @portabletext/editor@3.3.2
-
-## 3.0.21
-
-### Patch Changes
-
-- Updated dependencies [[`8facc13`](https://github.com/portabletext/editor/commit/8facc139f0ae1411e7383b4eddf168a5fae1fca9)]:
- - @portabletext/editor@3.3.1
-
-## 3.0.20
-
-### Patch Changes
-
-- Updated dependencies [[`4d5f86f`](https://github.com/portabletext/editor/commit/4d5f86feb57512bbdf3ec85af92864297b5b6965)]:
- - @portabletext/editor@3.3.0
-
-## 3.0.19
-
-### Patch Changes
-
-- Updated dependencies [[`9d7229a`](https://github.com/portabletext/editor/commit/9d7229acd78fb5a115a2b1c6fe34f208d2a013c0)]:
- - @portabletext/editor@3.2.6
-
-## 3.0.18
-
-### Patch Changes
-
-- [#1961](https://github.com/portabletext/editor/pull/1961) [`b99833c`](https://github.com/portabletext/editor/commit/b99833c77502e8f1bfa59c80522b2ee22585a8b6) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @sanity/schema to ^4.20.3
-
-- Updated dependencies [[`b99833c`](https://github.com/portabletext/editor/commit/b99833c77502e8f1bfa59c80522b2ee22585a8b6), [`fef5b3c`](https://github.com/portabletext/editor/commit/fef5b3c75beb2063704257428e5a817bce6e66db)]:
- - @portabletext/editor@3.2.5
-
-## 3.0.17
-
-### Patch Changes
-
-- [#1955](https://github.com/portabletext/editor/pull/1955) [`5aff467`](https://github.com/portabletext/editor/commit/5aff467d3a0a607514224edcc2ed6ea3a8b17b4b) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.20.2
-
-- [#1957](https://github.com/portabletext/editor/pull/1957) [`4be12e4`](https://github.com/portabletext/editor/commit/4be12e44447d8dc749c8efe4e76de26f4c0300f6) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @sanity/types to ^4.20.3
-
-- Updated dependencies [[`5aff467`](https://github.com/portabletext/editor/commit/5aff467d3a0a607514224edcc2ed6ea3a8b17b4b), [`4be12e4`](https://github.com/portabletext/editor/commit/4be12e44447d8dc749c8efe4e76de26f4c0300f6), [`ba41b1d`](https://github.com/portabletext/editor/commit/ba41b1dba6b3cc33eb48bfcd052c15d84e6cf46d)]:
- - @portabletext/editor@3.2.4
-
-## 3.0.16
-
-### Patch Changes
-
-- [#1933](https://github.com/portabletext/editor/pull/1933) [`ba5c3f6`](https://github.com/portabletext/editor/commit/ba5c3f6943f4d23ba102b97fedf4fa7e787ca6e6) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.20.1
-
-- Updated dependencies [[`ba5c3f6`](https://github.com/portabletext/editor/commit/ba5c3f6943f4d23ba102b97fedf4fa7e787ca6e6), [`5f98a44`](https://github.com/portabletext/editor/commit/5f98a4473ca11d524975a7b65f0b9ebc9c0aa97d), [`9f510fa`](https://github.com/portabletext/editor/commit/9f510fabcba5b98b56c26701738243118e9d1e27)]:
- - @portabletext/editor@3.2.3
-
-## 3.0.15
-
-### Patch Changes
-
-- [#1944](https://github.com/portabletext/editor/pull/1944) [`93edd06`](https://github.com/portabletext/editor/commit/93edd06478ec0748242a652668af5b90b87d9d45) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update react monorepo to ^19.2.1
-
-- Updated dependencies [[`93edd06`](https://github.com/portabletext/editor/commit/93edd06478ec0748242a652668af5b90b87d9d45)]:
- - @portabletext/editor@3.2.2
-
-## 3.0.14
-
-### Patch Changes
-
-- Updated dependencies [[`2ad036f`](https://github.com/portabletext/editor/commit/2ad036f27f00ac156351620fdfb537097b02e9ef)]:
- - @portabletext/editor@3.2.1
-
-## 3.0.13
-
-### Patch Changes
-
-- Updated dependencies [[`9513ef4`](https://github.com/portabletext/editor/commit/9513ef4f5596b13e4d7c8c794ec5c303c46ddb0e)]:
- - @portabletext/editor@3.2.0
-
-## 3.0.12
-
-### Patch Changes
-
-- [#1930](https://github.com/portabletext/editor/pull/1930) [`d7a7c89`](https://github.com/portabletext/editor/commit/d7a7c892b929194dcc335a7e291e0a9c20c5160e) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.20.0
-
-- Updated dependencies [[`87a9d7a`](https://github.com/portabletext/editor/commit/87a9d7abac3895e35ebb9d68a75185f65fec0dcd), [`93509e8`](https://github.com/portabletext/editor/commit/93509e84652df14a488070dc2c3a7cca0e252e5f), [`d7a7c89`](https://github.com/portabletext/editor/commit/d7a7c892b929194dcc335a7e291e0a9c20c5160e)]:
- - @portabletext/editor@3.1.2
-
-## 3.0.11
-
-### Patch Changes
-
-- Updated dependencies [[`77443af`](https://github.com/portabletext/editor/commit/77443afe9941200f7eea5b22882c32d3426a883a)]:
- - @portabletext/editor@3.1.1
-
-## 3.0.10
-
-### Patch Changes
-
-- Updated dependencies [[`c03200f`](https://github.com/portabletext/editor/commit/c03200f174b42f7b36ecb9c21c133b9848b46d90), [`6d038fd`](https://github.com/portabletext/editor/commit/6d038fdce591eedde45f73790678fbf6337ab675), [`817a538`](https://github.com/portabletext/editor/commit/817a538f860870b6d8275a22a3a6ca64300cf335)]:
- - @portabletext/editor@3.1.0
-
-## 3.0.9
-
-### Patch Changes
-
-- Updated dependencies [[`b0b7383`](https://github.com/portabletext/editor/commit/b0b7383acc93132b829abaffd0edb1280a223636), [`ccea206`](https://github.com/portabletext/editor/commit/ccea206accfbd7e9774daa03e9cb3bc444161cc4), [`4d94aa6`](https://github.com/portabletext/editor/commit/4d94aa684d2eaa95762652300660ecb86c333178)]:
- - @portabletext/editor@3.0.9
-
-## 3.0.8
-
-### Patch Changes
-
-- [#1913](https://github.com/portabletext/editor/pull/1913) [`cb190ec`](https://github.com/portabletext/editor/commit/cb190ec4d90e7ba2b4805e993b138436f7c1c83b) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.19.0
-
-- Updated dependencies [[`cb190ec`](https://github.com/portabletext/editor/commit/cb190ec4d90e7ba2b4805e993b138436f7c1c83b), [`99e1cd5`](https://github.com/portabletext/editor/commit/99e1cd59ff740c3089124debd805fde0f78aaaee), [`b9248d1`](https://github.com/portabletext/editor/commit/b9248d16869ec77299c7bc19ec34ac1bcbab03d5)]:
- - @portabletext/editor@3.0.8
-
-## 3.0.7
-
-### Patch Changes
-
-- [#1908](https://github.com/portabletext/editor/pull/1908) [`5fec0bd`](https://github.com/portabletext/editor/commit/5fec0bdefe69bef404037c57e7668e049434fc06) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.18.0
-
-- Updated dependencies [[`5fec0bd`](https://github.com/portabletext/editor/commit/5fec0bdefe69bef404037c57e7668e049434fc06), [`9b228fd`](https://github.com/portabletext/editor/commit/9b228fdd4433461c802feb86b2b35361a95a4577)]:
- - @portabletext/editor@3.0.7
-
-## 3.0.6
-
-### Patch Changes
-
-- [#1904](https://github.com/portabletext/editor/pull/1904) [`72f4cfb`](https://github.com/portabletext/editor/commit/72f4cfb74101aa176a094f440b81a51b748333c8) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.17.0
-
-- Updated dependencies [[`72f4cfb`](https://github.com/portabletext/editor/commit/72f4cfb74101aa176a094f440b81a51b748333c8), [`6298c34`](https://github.com/portabletext/editor/commit/6298c34c0eac5e4a87b97fe8fed22bce81155d88)]:
- - @portabletext/editor@3.0.6
-
-## 3.0.5
-
-### Patch Changes
-
-- [#1875](https://github.com/portabletext/editor/pull/1875) [`9ac5955`](https://github.com/portabletext/editor/commit/9ac5955011432373fb1eddf1e9501ea9d49cb667) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.16.0
-
-- Updated dependencies [[`9ac5955`](https://github.com/portabletext/editor/commit/9ac5955011432373fb1eddf1e9501ea9d49cb667)]:
- - @portabletext/editor@3.0.5
-
-## 3.0.4
-
-### Patch Changes
-
-- Updated dependencies [[`8553515`](https://github.com/portabletext/editor/commit/85535157db06a3535961f8d3bc41a3f3e53220ec), [`d723c0a`](https://github.com/portabletext/editor/commit/d723c0a1e0e224167dfe98bb9de786cc7d5e1774)]:
- - @portabletext/editor@3.0.4
-
-## 3.0.3
-
-### Patch Changes
-
-- Updated dependencies [[`348de8e`](https://github.com/portabletext/editor/commit/348de8e0b8e8557ffb998575c6f533ecba87774d)]:
- - @portabletext/editor@3.0.3
-
-## 3.0.2
-
-### Patch Changes
-
-- Updated dependencies [[`adf1465`](https://github.com/portabletext/editor/commit/adf1465b4e99e3c2215442ab76e45fafbf08afa1)]:
- - @portabletext/editor@3.0.2
-
-## 3.0.1
-
-### Patch Changes
-
-- Updated dependencies [[`4cf086e`](https://github.com/portabletext/editor/commit/4cf086e9ed97d8b2fc2010ad9af6c7db7d75aa7a), [`4a6dabd`](https://github.com/portabletext/editor/commit/4a6dabd527d286d3f7e6cc04dc93f3391f11a6c3), [`1c257be`](https://github.com/portabletext/editor/commit/1c257be04dacf0b3d2ff25c3b995d901ce17bf7e), [`9668d22`](https://github.com/portabletext/editor/commit/9668d220072b9969f71818179a668e11d8479975), [`57aa71e`](https://github.com/portabletext/editor/commit/57aa71ecdf0d376d8afbec5d7f53e542257cdc55), [`41dbb85`](https://github.com/portabletext/editor/commit/41dbb85fe6d686e7fa25d20e84e72e8b7171efc8)]:
- - @portabletext/editor@3.0.1
-
-## 3.0.0
-
-### Patch Changes
-
-- Updated dependencies [[`0454f2f`](https://github.com/portabletext/editor/commit/0454f2f7f014b327c53832b3e3d16d87b614eebb), [`c8cb899`](https://github.com/portabletext/editor/commit/c8cb899ca71a0462ea74d631916c6af71dc81993), [`b5046ce`](https://github.com/portabletext/editor/commit/b5046ce61982b35b3f4851aed708e495e7b9724f), [`12f50bd`](https://github.com/portabletext/editor/commit/12f50bd1a9db16da161beab737030ea204d34d5c), [`849a881`](https://github.com/portabletext/editor/commit/849a881bccc6aa619d6a98e9d39e3256db210a6a), [`7c209bd`](https://github.com/portabletext/editor/commit/7c209bd975f08406c6ef2afad134440932ad3b6b), [`ea8ad76`](https://github.com/portabletext/editor/commit/ea8ad76c379c7cf9cd451b3a3191ef2c23d5541f)]:
- - @portabletext/editor@3.0.0
-
-## 2.0.10
-
-### Patch Changes
-
-- Updated dependencies [[`aaac0b5`](https://github.com/portabletext/editor/commit/aaac0b58dd2f0959317787e751f64e9f3772403b)]:
- - @portabletext/editor@2.21.3
-
-## 2.0.9
-
-### Patch Changes
-
-- Updated dependencies [[`585f6e1`](https://github.com/portabletext/editor/commit/585f6e1c473ce025bd478341208ae86416d2ec7c)]:
- - @portabletext/editor@2.21.2
-
-## 2.0.8
-
-### Patch Changes
-
-- Updated dependencies [[`3e12791`](https://github.com/portabletext/editor/commit/3e12791fb73989811b411ace6a3d4161b984959f), [`46b5503`](https://github.com/portabletext/editor/commit/46b5503806ce8435fb55ead3a901b41581ac5631)]:
- - @portabletext/editor@2.21.1
-
-## 2.0.7
-
-### Patch Changes
-
-- [#1858](https://github.com/portabletext/editor/pull/1858) [`746acd3`](https://github.com/portabletext/editor/commit/746acd3a64cd8d05ee171e069f2a20c35a4e1ccf) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.14.2
-
-- Updated dependencies [[`746acd3`](https://github.com/portabletext/editor/commit/746acd3a64cd8d05ee171e069f2a20c35a4e1ccf), [`9a98716`](https://github.com/portabletext/editor/commit/9a987169735f6ec97d916cf4ed0ea4f1da48dd72)]:
- - @portabletext/editor@2.21.0
-
-## 2.0.6
-
-### Patch Changes
-
-- Updated dependencies [[`d1abdbc`](https://github.com/portabletext/editor/commit/d1abdbc4cb7aef5922086e3bd446ec7b24663343), [`2b87d38`](https://github.com/portabletext/editor/commit/2b87d387ee39f12202bcae3a1d7e82a7fc3729b9), [`f4021e5`](https://github.com/portabletext/editor/commit/f4021e53f862686bcaac087c2ff1a7033a797d04)]:
- - @portabletext/editor@2.20.0
-
-## 2.0.5
-
-### Patch Changes
-
-- [#1843](https://github.com/portabletext/editor/pull/1843) [`c0075a3`](https://github.com/portabletext/editor/commit/c0075a34e2d17a2616461ac6789daf52740926c1) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.14.1
-
-- Updated dependencies [[`c0075a3`](https://github.com/portabletext/editor/commit/c0075a34e2d17a2616461ac6789daf52740926c1), [`e868069`](https://github.com/portabletext/editor/commit/e868069c8eab8e803e0da6d7a9376001f4a7363f)]:
- - @portabletext/editor@2.19.3
-
-## 2.0.4
-
-### Patch Changes
-
-- [#1844](https://github.com/portabletext/editor/pull/1844) [`dd80369`](https://github.com/portabletext/editor/commit/dd80369dcb68b1d6910828a90a8ce5bf3e5fb5d6) Thanks [@stipsan](https://github.com/stipsan)! - fix: add support for react 18
-
-- Updated dependencies []:
- - @portabletext/editor@2.19.2
-
-## 2.0.3
-
-### Patch Changes
-
-- Updated dependencies [[`b669b14`](https://github.com/portabletext/editor/commit/b669b14cc70a12c22a0726bc8e1cb31e336acdbc)]:
- - @portabletext/editor@2.19.1
-
-## 2.0.2
-
-### Patch Changes
-
-- Updated dependencies [[`ae4fd2c`](https://github.com/portabletext/editor/commit/ae4fd2cc37b87d26f2db7a09c20c41486c88ace8)]:
- - @portabletext/editor@2.19.0
-
-## 2.0.1
-
-### Patch Changes
-
-- Updated dependencies [[`b4c729c`](https://github.com/portabletext/editor/commit/b4c729cfaa4429c6de8e50ece79e6da2175a5e35), [`5e5d349`](https://github.com/portabletext/editor/commit/5e5d349f9d45dd472fa69820d20067b3020a03bb)]:
- - @portabletext/editor@2.18.1
-
-## 2.0.0
-
-### Major Changes
-
-- [#1814](https://github.com/portabletext/editor/pull/1814) [`e3c26cb`](https://github.com/portabletext/editor/commit/e3c26cb4a68fdc3e563f9b025c4af04678202b89) Thanks [@stipsan](https://github.com/stipsan)! - Require node v20.19 or later, or v22.12 or later
-
-### Minor Changes
-
-- [#1814](https://github.com/portabletext/editor/pull/1814) [`e3c26cb`](https://github.com/portabletext/editor/commit/e3c26cb4a68fdc3e563f9b025c4af04678202b89) Thanks [@stipsan](https://github.com/stipsan)! - Remove CJS exports, this package is now ESM-only
-
-### Patch Changes
-
-- [#1814](https://github.com/portabletext/editor/pull/1814) [`e3c26cb`](https://github.com/portabletext/editor/commit/e3c26cb4a68fdc3e563f9b025c4af04678202b89) Thanks [@stipsan](https://github.com/stipsan)! - Upgrade @sanity/pkg-utils to v9
-
-- [#1808](https://github.com/portabletext/editor/pull/1808) [`e7f0d69`](https://github.com/portabletext/editor/commit/e7f0d6993abbdf2a6aeecad22bab970c0810eca1) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.13.0
-
-- Updated dependencies [[`e3c26cb`](https://github.com/portabletext/editor/commit/e3c26cb4a68fdc3e563f9b025c4af04678202b89), [`e7f0d69`](https://github.com/portabletext/editor/commit/e7f0d6993abbdf2a6aeecad22bab970c0810eca1), [`e3c26cb`](https://github.com/portabletext/editor/commit/e3c26cb4a68fdc3e563f9b025c4af04678202b89)]:
- - @portabletext/editor@2.18.0
-
-## 1.0.21
-
-### Patch Changes
-
-- Updated dependencies [[`ab4ac2d`](https://github.com/portabletext/editor/commit/ab4ac2d5dd29c65cdab7c328bdae70665d36bb9e)]:
- - @portabletext/editor@2.17.2
-
-## 1.0.20
-
-### Patch Changes
-
-- Updated dependencies [[`5beedd2`](https://github.com/portabletext/editor/commit/5beedd2778149a70e5e6464c28da8e31d9bef3ac), [`fdac1f0`](https://github.com/portabletext/editor/commit/fdac1f0f5fc264dff703b0b6e814e407964004ad)]:
- - @portabletext/editor@2.17.1
-
-## 1.0.19
-
-### Patch Changes
-
-- Updated dependencies [[`5442326`](https://github.com/portabletext/editor/commit/5442326569c145a0c146d2523f99ca245bf92623)]:
- - @portabletext/editor@2.17.0
-
-## 1.0.18
-
-### Patch Changes
-
-- [#1788](https://github.com/portabletext/editor/pull/1788) [`5f4cac4`](https://github.com/portabletext/editor/commit/5f4cac440d766cf8415e7392dc9f72e6327fdb8c) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.12.0
-
-- Updated dependencies [[`9aee71a`](https://github.com/portabletext/editor/commit/9aee71a463dbcaadc0037170addb23f28ba40250), [`5f4cac4`](https://github.com/portabletext/editor/commit/5f4cac440d766cf8415e7392dc9f72e6327fdb8c), [`31f61c4`](https://github.com/portabletext/editor/commit/31f61c49607b141a1500e5ec3b9703e7cdf1786c), [`db80acc`](https://github.com/portabletext/editor/commit/db80acc5a189d45069d30b4bfc98c42d8ff88f67), [`dc886f5`](https://github.com/portabletext/editor/commit/dc886f586c9f0d70a5650e438a0407366a5e60a6)]:
- - @portabletext/editor@2.16.0
-
-## 1.0.17
-
-### Patch Changes
-
-- Updated dependencies [[`75b4c38`](https://github.com/portabletext/editor/commit/75b4c38be8b82aaa9d6f86ba97ba551ee2a83255)]:
- - @portabletext/editor@2.15.5
-
-## 1.0.16
-
-### Patch Changes
-
-- Updated dependencies [[`851cad1`](https://github.com/portabletext/editor/commit/851cad1a5e77ff4f069f1882e5a147b461e9e04a)]:
- - @portabletext/editor@2.15.4
-
-## 1.0.15
-
-### Patch Changes
-
-- Updated dependencies [[`777b61b`](https://github.com/portabletext/editor/commit/777b61ba6c25f6a543e1a3111ad8978072999b3e)]:
- - @portabletext/editor@2.15.3
-
-## 1.0.14
-
-### Patch Changes
-
-- Updated dependencies [[`e84f3e5`](https://github.com/portabletext/editor/commit/e84f3e5c3070044692a7bfaa40481c79e40a4893), [`84247b1`](https://github.com/portabletext/editor/commit/84247b1efcbaf61aa16e0d76b1079a8405dde82b), [`86b46a4`](https://github.com/portabletext/editor/commit/86b46a469c2afc1b1795aab28f5f85420a87fb59), [`fac8c2e`](https://github.com/portabletext/editor/commit/fac8c2eedea8c3fdd1f3fa496663d172b4de18f4)]:
- - @portabletext/editor@2.15.2
-
-## 1.0.13
-
-### Patch Changes
-
-- [#1757](https://github.com/portabletext/editor/pull/1757) [`657f0e1`](https://github.com/portabletext/editor/commit/657f0e13138f51f1c8aa5a249b9c2ffa0fe0fb65) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.11.0
-
-- Updated dependencies [[`657f0e1`](https://github.com/portabletext/editor/commit/657f0e13138f51f1c8aa5a249b9c2ffa0fe0fb65), [`73c1f43`](https://github.com/portabletext/editor/commit/73c1f43d13f1adf8aad8db03597e4e858a3a41e2)]:
- - @portabletext/editor@2.15.1
-
-## 1.0.12
-
-### Patch Changes
-
-- Updated dependencies [[`f9b0849`](https://github.com/portabletext/editor/commit/f9b0849c4cf5de298fb8133230d9d14ff780e25d), [`79e3e98`](https://github.com/portabletext/editor/commit/79e3e983fae9eb3106d7741d877ff99a76d7fde5), [`36615f3`](https://github.com/portabletext/editor/commit/36615f3c42805434e5e597587a4c1e2fac73c75e)]:
- - @portabletext/editor@2.15.0
-
-## 1.0.11
-
-### Patch Changes
-
-- [#1745](https://github.com/portabletext/editor/pull/1745) [`82bb94d`](https://github.com/portabletext/editor/commit/82bb94d998445f0b79c215d6ab1f3eed56c020fc) Thanks [@stipsan](https://github.com/stipsan)! - Upgrade React Compiler to v1
-
-- Updated dependencies [[`9d6cfdb`](https://github.com/portabletext/editor/commit/9d6cfdbe3fc67d88113da7f73b408f3185ddabef), [`82bb94d`](https://github.com/portabletext/editor/commit/82bb94d998445f0b79c215d6ab1f3eed56c020fc), [`a8a3fad`](https://github.com/portabletext/editor/commit/a8a3faddb5217fde30df34bd175e99e709983ff6)]:
- - @portabletext/editor@2.14.4
-
-## 1.0.10
-
-### Patch Changes
-
-- Updated dependencies [[`54f57e3`](https://github.com/portabletext/editor/commit/54f57e3e85cc5544c5d18881c393957218ffb34a)]:
- - @portabletext/editor@2.14.3
-
-## 1.0.9
-
-### Patch Changes
-
-- [#1729](https://github.com/portabletext/editor/pull/1729) [`7eab00e`](https://github.com/portabletext/editor/commit/7eab00ee9b1f1186fdac76210daa1953edc2847c) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update sanity monorepo to ^4.10.3
-
-- Updated dependencies [[`7eab00e`](https://github.com/portabletext/editor/commit/7eab00ee9b1f1186fdac76210daa1953edc2847c)]:
- - @portabletext/editor@2.14.2
-
-## 1.0.8
-
-### Patch Changes
-
-- Updated dependencies [[`13a2c63`](https://github.com/portabletext/editor/commit/13a2c6337cc48773fe84baaa5f6ddbbc9502b683), [`0e90027`](https://github.com/portabletext/editor/commit/0e90027a750c49f0dfa1273b26b367fbbc20f59c), [`4041334`](https://github.com/portabletext/editor/commit/4041334f4474b00b275f94532e4baddcc1b906ab)]:
- - @portabletext/editor@2.14.1
-
-## 1.0.7
-
-### Patch Changes
-
-- [#1722](https://github.com/portabletext/editor/pull/1722) [`b7c1e14`](https://github.com/portabletext/editor/commit/b7c1e14ca63990adf2cec0fb858fd9170ae86518) Thanks [@christianhg](https://github.com/christianhg)! - fix: move plugin to editor repository
-
-## 1.0.6
-
-### Patch Changes
-
-- [#100](https://github.com/portabletext/plugins/pull/100) [`afc2ce0`](https://github.com/portabletext/plugins/commit/afc2ce0047bc66fe84adb6324efddc5fea182a71) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update react monorepo
-
-## 1.0.5
-
-### Patch Changes
-
-- [#102](https://github.com/portabletext/plugins/pull/102) [`a0371f1`](https://github.com/portabletext/plugins/commit/a0371f122f95a3bb38907230c53ee5f2c559dd18) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @portabletext/editor to ^2.6.9
-
-## 1.0.4
-
-### Patch Changes
-
-- [#103](https://github.com/portabletext/plugins/pull/103) [`e473911`](https://github.com/portabletext/plugins/commit/e4739110312b43c04631f64811621091719aa33f) Thanks [@ecoscript](https://github.com/apps/ecoscript)! - fix(deps): update React Compiler dependencies 🤖 ✨
-
-- [`6167380`](https://github.com/portabletext/plugins/commit/61673805b83e5c54163e22beeb98f02df7f0c231) Thanks [@stipsan](https://github.com/stipsan)! - react-compiler-runtime isn't needed
-
-## 1.0.3
-
-### Patch Changes
-
-- [#91](https://github.com/portabletext/plugins/pull/91) [`bdc2e97`](https://github.com/portabletext/plugins/commit/bdc2e971c796e1861c4fbf53bb81b4614f60fa49) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @sanity/sdk-react to ^2.1.2
-
-- [`ac0c150`](https://github.com/portabletext/plugins/commit/ac0c150e769500d39a598b0a3da74617a3f29701) Thanks [@stipsan](https://github.com/stipsan)! - Upgrade react compiler to rc 2
-
-## 1.0.2
-
-### Patch Changes
-
-- [#92](https://github.com/portabletext/plugins/pull/92) [`2a4179a`](https://github.com/portabletext/plugins/commit/2a4179a5d76028180f722fd126aa4c41503d10f5) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @portabletext/editor to ^2.4.1
-
-## [1.0.1](https://github.com/portabletext/plugins/compare/plugin-sdk-value-v1.0.0...plugin-sdk-value-v1.0.1) (2025-08-20)
-
-### Bug Fixes
-
-- **deps:** update dependency @portabletext/editor to ^1.58.0 ([a5f36da](https://github.com/portabletext/plugins/commit/a5f36dac0dc2cd6fcfa5c1d5a257226a5ee4ffbd))
-- **deps:** update dependency @portabletext/editor to ^2.1.11 ([cf70d4f](https://github.com/portabletext/plugins/commit/cf70d4f7348339b89fd20f64798a0cb6966847d8))
-- **deps:** update dependency @portabletext/editor to v2 ([52841e5](https://github.com/portabletext/plugins/commit/52841e5beea4a906bd0659c816c3269660110e9b))
-- **deps:** update dependency @sanity/sdk-react to ^2.1.1 ([2b61b01](https://github.com/portabletext/plugins/commit/2b61b010449540c9597d8ed6b315e10810107021))
-
-## 1.0.0 (2025-07-02)
-
-### Features
-
-- introduce @portabletext/plugin-sdk-value ([a236c90](https://github.com/portabletext/plugins/commit/a236c90c9a44cd345401e34cb9a8f0c6eb20a62b))
-
-## Changelog
diff --git a/packages/plugin-sdk-value/README.md b/packages/plugin-sdk-value/README.md
deleted file mode 100644
index 5da2ef0539..0000000000
--- a/packages/plugin-sdk-value/README.md
+++ /dev/null
@@ -1,206 +0,0 @@
-# `@portabletext/plugin-sdk-value`
-
-> Connect a Portable Text Editor with a Sanity document using the SDK
-
-Two-way synchronization between a Portable Text Editor and a field in a Sanity
-document, plus presence and inline comments: other people's carets show up in
-the field and the local user's caret shows up for them, and comment threads
-anchored to text draw as highlights, all interoperating with the Studio.
-
-## Installation
-
-```sh
-npm install @portabletext/plugin-sdk-value
-```
-
-## Features
-
-- **Two-way synchronization**: Changes in the editor update the document, and document changes update the editor
-- **Real-time updates**: Automatically handles patches from external sources (other users, mutations, etc.)
-- **Optimistic updates**: Provides smooth user experience with immediate local updates
-- **Presence**: Reports where the local user is editing, and draws other people's carets
-- **Inline comments**: Draws highlights for comment threads anchored to text, and starts new threads on the selection
-
-## Usage
-
-Use `SDKPortableTextEditable` in place of `PortableTextEditable`, inside the
-`EditorProvider`. It names the document and field once and wires up value sync,
-presence reporting, and remote carets:
-
-```tsx
-import {defineSchema, EditorProvider} from '@portabletext/editor'
-import {SDKPortableTextEditable} from '@portabletext/plugin-sdk-value'
-
-function MyEditor() {
- return (
-
-
-
- )
-}
-```
-
-That is all of it. Remote carets are drawn with a built-in caret, so nothing has
-to be styled to get presence working.
-
-Every other prop is forwarded to `PortableTextEditable` untouched. Any
-`rangeDecorations` you pass are kept and merged with the presence carets rather
-than replaced.
-
-### Styling the caret
-
-The built-in caret is deliberately plain: a coloured line with a dot above it and
-the participant's name on hover. Colours come from a small fixed palette, keyed on
-the user, so one person in two tabs gets one colour. Pass `renderCursor` to
-replace it:
-
-```tsx nocheck
-
- (props) => (
- {props.children}
- )}
-/>
-```
-
-Your component receives the decorated text as `children` and should render it.
-Pass `renderCursor={null}` to draw no carets at all while still reporting the
-local user's presence, which is what you want if you only care about keeping the
-document in sync.
-
-### Inline comments
-
-Comment threads anchored to text in the field draw as highlights, and new
-threads can be started on the current selection. The composer UI stays with the
-app, the same split presence uses for carets. Comments are written in the shape
-Sanity Studio stores, so threads round-trip between an SDK app and the Studio.
-
-`useSDKCommentDecorations` returns `RangeDecoration[]` for the open threads on
-the field. Pass it through `rangeDecorations`, which `SDKPortableTextEditable`
-merges with the presence carets:
-
-```tsx nocheck
-const decorations = useSDKCommentDecorations({
- ...documentHandle,
- path: 'content',
- renderDecoration: (comment) => (props) => (
-
- {props.children}
-
- ),
-})
-
-return (
-
-)
-```
-
-`useSDKCommentAuthoring` is the write side: `commentableSelection` is set when
-the current selection can take a comment, and `createInlineComment` starts a
-thread anchored to it:
-
-```tsx nocheck
-import {useSDKCommentAuthoring} from '@portabletext/plugin-sdk-value'
-
-const {commentableSelection, createInlineComment} = useSDKCommentAuthoring({
- ...documentHandle,
- path: 'content',
-})
-
-// Show the composer while `commentableSelection` is set, then:
-await createInlineComment({message})
-```
-
-Highlights follow the text while the user types, and a highlight whose text is
-deleted or rewritten beyond recognition is dropped rather than drawn on the
-wrong words. Resolved threads draw nothing, matching the Studio.
-
-### Rendering the editable yourself
-
-`SDKValuePlugin` still works as a sibling component if you would rather keep
-control of `PortableTextEditable`. Pair it with `SDKPresencePlugin` to report
-presence, and `useSDKPresenceCursors` for remote carets:
-
-```tsx nocheck
-import {
- defineSchema,
- EditorProvider,
- PortableTextEditable,
-} from '@portabletext/editor'
-import {
- SDKPresencePlugin,
- SDKValuePlugin,
- useSDKPresenceCursors,
-} from '@portabletext/plugin-sdk-value'
-
-function MyEditor(props: DocumentHandle) {
- const cursors = useSDKPresenceCursors({
- ...props,
- path: 'content',
- renderCursor:
- ({user}) =>
- (cursorProps) => {cursorProps.children},
- })
-
- return (
-
-
-
-
-
- )
-}
-```
-
-## Props
-
-`SDKPortableTextEditable` accepts a
-[Document Handle](https://www.sanity.io/docs/app-sdk/document-handles), every
-`PortableTextEditable` prop, and:
-
-| Prop | Type | Description |
-| -------------- | ----------------------------- | -------------------------------------------------------------------------------- |
-| `documentId` | `string` | The document ID |
-| `documentType` | `string` | The document type |
-| `path` | `string` | [JSONMatch][json-match] path expression to the Portable Text field |
-| `renderCursor` | `function \| null` (optional) | Draws one remote participant's caret. Omit for the built-in one, `null` for none |
-| `dataset` | `string` (optional) | Dataset name (if different from configured default) |
-| `projectId` | `string` (optional) | Project ID (if different from configured default) |
-| `perspective` | `string \| object` (optional) | Which document to sync and report: draft, published, or a release |
-
-[json-match]: https://www.sanity.io/docs/content-lake/json-match
-
-## Notes on presence
-
-Carets are drawn with the built-in component unless you pass `renderCursor`, and
-are collapsed to a single point at the participant's focus. Presence
-answers where someone is, so decorating their whole selection would highlight
-text the local user never selected. The Studio does the same.
-
-Participants are counted by session, not by person. The same user in two tabs
-draws two carets, in the same colour. Group by `user.sanityUserId` in your own
-`renderCursor` if you would rather show one.
-
-The local user is never included, so an app does not draw its own caret.
-
-Which document is reported follows the handle's `perspective`, or the ambient one
-from `ResourceProvider`. Pass the plain document id and let the perspective
-select the draft, the published document, or a release version. This matters for
-the Studio, whose field indicators compare the exact document id its form is on.
-
-## Requirements
-
-This plugin requires:
-
-- `@sanity/sdk-react` 2.20.1 or newer, where the comment hooks were added
-- The document must exist in the Sanity dataset
diff --git a/packages/plugin-sdk-value/package.config.ts b/packages/plugin-sdk-value/package.config.ts
deleted file mode 100644
index dda8077cc3..0000000000
--- a/packages/plugin-sdk-value/package.config.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import {defineConfig} from '@sanity/pkg-utils'
-
-export default defineConfig({
- tsconfig: 'tsconfig.dist.json',
- reactCompiler: {transform: 'oxc', target: '19'},
-})
diff --git a/packages/plugin-sdk-value/package.json b/packages/plugin-sdk-value/package.json
deleted file mode 100644
index e201f18c25..0000000000
--- a/packages/plugin-sdk-value/package.json
+++ /dev/null
@@ -1,101 +0,0 @@
-{
- "name": "@portabletext/plugin-sdk-value",
- "version": "8.1.20",
- "description": "Connect a Portable Text Editor with a Sanity document using the SDK",
- "keywords": [
- "@sanity/sdk",
- "@sanity/sdk-react",
- "plugin",
- "portabletext",
- "sdk",
- "sync",
- "value"
- ],
- "homepage": "https://portabletext.org",
- "bugs": {
- "url": "https://github.com/portabletext/editor/issues"
- },
- "license": "MIT",
- "author": "Sanity.io ",
- "repository": {
- "type": "git",
- "url": "https://github.com/portabletext/editor.git",
- "directory": "packages/plugin-sdk-value"
- },
- "files": [
- "dist"
- ],
- "type": "module",
- "sideEffects": false,
- "types": "./dist/index.d.ts",
- "exports": {
- ".": {
- "source": "./src/index.ts",
- "default": "./dist/index.js"
- },
- "./package.json": "./package.json"
- },
- "publishConfig": {
- "exports": {
- ".": "./dist/index.js",
- "./package.json": "./package.json"
- }
- },
- "scripts": {
- "build": "pkg-utils build --strict --check",
- "check:types": "tsc",
- "check:types:watch": "tsc --watch",
- "clean": "del .turbo && del dist && del node_modules",
- "dev": "pkg-utils watch",
- "prepublishOnly": "turbo run build",
- "test:browser": "vitest --run --project browser",
- "test:browser:chromium": "vitest --run --project \"browser (chromium)\"",
- "test:browser:chromium:watch": "vitest --project \"browser (chromium)\"",
- "test:browser:firefox": "vitest --run --project \"browser (firefox)\"",
- "test:browser:firefox:watch": "vitest --project \"browser (firefox)\"",
- "test:browser:webkit": "vitest --run --project \"browser (webkit)\"",
- "test:browser:webkit:watch": "vitest --project \"browser (webkit)\"",
- "test:unit": "vitest --run --project unit",
- "test:unit:watch": "vitest --project unit",
- "test:watch": "vitest"
- },
- "dependencies": {
- "@portabletext/patches": "workspace:^",
- "@sanity/diff-match-patch": "catalog:",
- "@sanity/diff-patch": "^6.0.0",
- "@sanity/json-match": "^1.0.5",
- "@xstate/react": "catalog:",
- "obug": "catalog:",
- "xstate": "catalog:"
- },
- "devDependencies": {
- "@portabletext/editor": "workspace:^",
- "@portabletext/schema": "workspace:^",
- "@portabletext/test": "workspace:^",
- "@sanity/pkg-utils": "catalog:tooling",
- "@sanity/sdk-react": "^3.11.0",
- "@sanity/tsconfig": "catalog:tooling",
- "@types/react": "catalog:tooling",
- "@types/react-dom": "catalog:tooling",
- "@vitejs/plugin-react": "catalog:tooling",
- "@vitest/browser": "catalog:tooling",
- "@vitest/browser-playwright": "catalog:tooling",
- "jsdom": "catalog:tooling",
- "oxc-transform-react": "catalog:tooling",
- "react": "catalog:",
- "react-dom": "catalog:",
- "typescript": "catalog:tooling",
- "vite": "catalog:tooling",
- "vitest": "catalog:tooling",
- "vitest-browser-react": "catalog:tooling"
- },
- "peerDependencies": {
- "@portabletext/editor": "workspace:^",
- "@sanity/sdk-react": "^2.20.1 || ^3",
- "react": "^19.2",
- "react-dom": "^19.2"
- },
- "engines": {
- "node": ">=22.12"
- }
-}
diff --git a/packages/plugin-sdk-value/src/comments-anchoring.test.ts b/packages/plugin-sdk-value/src/comments-anchoring.test.ts
deleted file mode 100644
index 8a5b3b31fa..0000000000
--- a/packages/plugin-sdk-value/src/comments-anchoring.test.ts
+++ /dev/null
@@ -1,255 +0,0 @@
-import {describe, expect, test} from 'vitest'
-import {
- COMMENT_INDICATORS,
- relativeCommentPath,
- resolveCommentSelections,
- type StoredTextSelection,
-} from './comments-anchoring'
-
-/**
- * The scenarios are ported from the Studio's
- * `buildRangeDecorationSelectionsFromComments` suite, fixtures included, so the
- * two implementations can be diffed against the same cases. One known gap the
- * Studio's suite also carries is pinned with `test.fails` below.
- */
-
-function span(_key: string, text: string) {
- return {_type: 'span', _key, marks: [], text}
-}
-
-function block(_key: string, children: ReturnType[]) {
- return {_key, _type: 'block', style: 'normal', markDefs: [], children}
-}
-
-function stored(text: string, _key = '6222e4072b6e'): StoredTextSelection {
- return {type: 'text', value: [{_key, text}]}
-}
-
-const MARKED = `Hello ${COMMENT_INDICATORS[0]}there${COMMENT_INDICATORS[1]} world`
-
-function resolve(value: unknown[], selection: StoredTextSelection) {
- return resolveCommentSelections({
- value,
- comments: [{commentId: 'c1', relativePath: [], selection}],
- }).map((anchored) => anchored.selection)
-}
-
-describe(resolveCommentSelections.name, () => {
- test('exact match between the stored text and the block', () => {
- const value = [
- block('6222e4072b6e', [span('9d9c95878a6e0', 'Hello there world')]),
- ]
-
- expect(resolve(value, stored(MARKED))).toEqual([
- {
- anchor: {
- offset: 6,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '9d9c95878a6e0'}],
- },
- focus: {
- offset: 11,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '9d9c95878a6e0'}],
- },
- },
- ])
- })
-
- test('text before the range was bolded, splitting the span', () => {
- const value = [
- block('6222e4072b6e', [
- span('9d9c95878a6e0', 'Hello'),
- span('5d176cf77466', ' there world'),
- ]),
- ]
-
- expect(resolve(value, stored(MARKED))).toEqual([
- {
- anchor: {
- offset: 1,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '5d176cf77466'}],
- },
- focus: {
- offset: 6,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '5d176cf77466'}],
- },
- },
- ])
- })
-
- test('text inside the range was bolded, splitting it across three spans', () => {
- const value = [
- block('6222e4072b6e', [
- span('9d9c95878a6e0', 'Hello th'),
- span('ea97036ed5c4', 'e'),
- span('8daa33e86194', 're world'),
- ]),
- ]
-
- expect(resolve(value, stored(MARKED))).toEqual([
- {
- anchor: {
- offset: 6,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '9d9c95878a6e0'}],
- },
- focus: {
- offset: 2,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '8daa33e86194'}],
- },
- },
- ])
- })
-
- test('bolding spans both inside and outside the range', () => {
- const value = [
- block('6222e4072b6e', [
- span('9d9c95878a6e0', 'Hel'),
- span('897d8881c889', 'lo th'),
- span('3b404dd88fc1', 'ere world'),
- ]),
- ]
-
- expect(resolve(value, stored(MARKED))).toEqual([
- {
- anchor: {
- offset: 3,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '897d8881c889'}],
- },
- focus: {
- offset: 3,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '3b404dd88fc1'}],
- },
- },
- ])
- })
-
- test('an edit inside the commented word grows the range to cover it', () => {
- const value = [
- block('6222e4072b6e', [span('9d9c95878a6e0', 'Hello the123re world')]),
- ]
-
- expect(resolve(value, stored(MARKED))).toEqual([
- {
- anchor: {
- offset: 6,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '9d9c95878a6e0'}],
- },
- focus: {
- offset: 14,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '9d9c95878a6e0'}],
- },
- },
- ])
- })
-
- test('a similar word added before the range does not steal the anchor', () => {
- const value = [
- block('6222e4072b6e', [span('9d9c95878a6e0', 'Hello where there world')]),
- ]
-
- expect(resolve(value, stored(MARKED))).toEqual([
- {
- anchor: {
- offset: 12,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '9d9c95878a6e0'}],
- },
- focus: {
- offset: 17,
- path: [{_key: '6222e4072b6e'}, 'children', {_key: '9d9c95878a6e0'}],
- },
- },
- ])
- })
-
- test('a comment whose block is gone resolves to nothing', () => {
- const value = [block('another-block', [span('s1', 'Hello there world')])]
-
- expect(resolve(value, stored(MARKED))).toEqual([])
- })
-
- // A known gap, carried by the Studio's own suite too: text typed
- // immediately after the range is absorbed into it. Pinned with `fails` so
- // this flips loudly if the algorithm ever gains the behaviour.
- test.fails('an edit immediately after the range does not expand it', () => {
- const value = [
- block('6222e4072b6e', [span('9d9c95878a6e0', 'Hello there123 world')]),
- ]
- expect(resolve(value, stored(MARKED))).toEqual([])
- })
-
- test('a dramatically changed block drops the anchor', () => {
- const value = [
- block('6222e4072b6e', [span('9d9c95878a6e0', 'Something else entirely')]),
- ]
- expect(resolve(value, stored(MARKED))).toEqual([])
- })
-
- test('a nested block resolves through its container path', () => {
- const value = [
- {
- _key: 'callout',
- _type: 'callout',
- content: [block('b1', [span('s1', 'Hello there world')])],
- },
- ]
-
- const anchored = resolveCommentSelections({
- value,
- comments: [
- {
- commentId: 'c1',
- relativePath: [{_key: 'callout'}, 'content'],
- selection: stored(MARKED, 'b1'),
- },
- ],
- })
-
- expect(anchored.map((a) => a.selection)).toEqual([
- {
- anchor: {
- offset: 6,
- path: [
- {_key: 'callout'},
- 'content',
- {_key: 'b1'},
- 'children',
- {_key: 's1'},
- ],
- },
- focus: {
- offset: 11,
- path: [
- {_key: 'callout'},
- 'content',
- {_key: 'b1'},
- 'children',
- {_key: 's1'},
- ],
- },
- },
- ])
- })
-})
-
-describe(relativeCommentPath.name, () => {
- test('reduces a stored field path to a path inside the editor', () => {
- expect(
- relativeCommentPath(['body'], 'body[_key=="callout"].content'),
- ).toEqual([{_key: 'callout'}, 'content'])
- })
-
- test('an exact match reduces to the empty path', () => {
- expect(relativeCommentPath(['body'], 'body')).toEqual([])
- })
-
- test("a sibling editor's comment does not match", () => {
- expect(relativeCommentPath(['body'], 'summary')).toBe(undefined)
- })
-
- test('an unparseable stored path is skipped rather than thrown on', () => {
- expect(relativeCommentPath(['body'], '[[[')).toBe(undefined)
- })
-
- test('an empty stored path is skipped', () => {
- expect(relativeCommentPath(['body'], '')).toBe(undefined)
- })
-})
diff --git a/packages/plugin-sdk-value/src/comments-anchoring.ts b/packages/plugin-sdk-value/src/comments-anchoring.ts
deleted file mode 100644
index bd6f50b23d..0000000000
--- a/packages/plugin-sdk-value/src/comments-anchoring.ts
+++ /dev/null
@@ -1,332 +0,0 @@
-import type {EditorSelection} from '@portabletext/editor'
-import {isEqualPaths, isKeyedSegment} from '@portabletext/editor/utils'
-import type {Path} from '@portabletext/patches'
-import {
- applyPatches,
- cleanupEfficiency,
- DIFF_DELETE,
- DIFF_EQUAL,
- DIFF_INSERT,
- makeDiff,
- makePatches,
- type Diff,
- type Patch,
-} from '@sanity/diff-match-patch'
-import {arrayifyPath} from './plugin.sdk-value'
-
-/**
- * How the Studio stores an inline comment's anchor: per Portable Text block the
- * selection touches, the block's entire plain text with these two private-use
- * characters inserted where the selection starts and ends. Text rather than
- * offsets, so the anchor can be re-found after the text around it changes.
- */
-export const COMMENT_INDICATORS = ['\uF000', '\uF001'] as const
-
-const COMMENT_INDICATORS_REGEX = new RegExp(
- `[${COMMENT_INDICATORS.join('')}]`,
- 'g',
-)
-
-/**
- * Inserted between spans when diffing, so a plain-text offset can be mapped
- * back to the span it belongs to afterwards.
- */
-const CHILD_SYMBOL = '\uF0D0'
-
-/**
- * Kept from the Studio implementation: high enough to avoid re-anchoring onto
- * the wrong occurrence of a repeated word, low enough not to hurt.
- */
-const DMP_MARGIN = 15
-
-/**
- * The stored anchor of one inline comment, in the shape the SDK returns it.
- * Structurally `CommentTextSelection` from `@sanity/sdk`, declared here so the
- * pure modules in this package stay import-light.
- */
-export interface StoredTextSelection {
- type: 'text'
- value: {_key: string; text: string}[]
-}
-
-export interface AnchoredComment {
- /** The comment's id, echoed back so the caller can correlate. */
- commentId: string
- /** Where the comment's text sits in the current editor value. */
- selection: NonNullable
-}
-
-interface ResolveOptions {
- /** The editor's current value. */
- value: unknown[]
- /**
- * Each comment's stored anchor, with its field path already reduced to the
- * path *inside* the editor: `[]` for a block directly in the decorated
- * field, or the keyed path of the containing array for a nested block.
- */
- comments: Array<{
- commentId: string
- relativePath: Path
- selection: StoredTextSelection
- }>
-}
-
-interface SpanLike {
- _key: string
- _type: string
- text?: string
-}
-
-interface TextBlockLike {
- _key: string
- children: SpanLike[]
-}
-
-function isTextBlock(node: unknown): node is TextBlockLike {
- return (
- typeof node === 'object' &&
- node !== null &&
- Array.isArray((node as TextBlockLike).children) &&
- typeof (node as TextBlockLike)._key === 'string'
- )
-}
-
-function isSpan(child: SpanLike): boolean {
- return child._type === 'span' && typeof child.text === 'string'
-}
-
-function getValueAtPath(value: unknown, path: Path): unknown {
- let current: unknown = value
- for (const segment of path) {
- if (current === null || typeof current !== 'object') {
- return undefined
- }
- if (typeof segment === 'string') {
- current = (current as Record)[segment]
- } else if (typeof segment === 'number') {
- current = Array.isArray(current) ? current[segment] : undefined
- } else if (isKeyedSegment(segment)) {
- current = Array.isArray(current)
- ? current.find(
- (item) =>
- typeof item === 'object' &&
- item !== null &&
- (item as {_key?: string})._key === segment._key,
- )
- : undefined
- } else {
- return undefined
- }
- }
- return current
-}
-
-function toPlainTextWithChildSeparators(block: TextBlockLike): string {
- return block.children
- .map((child) =>
- isSpan(child) ? (child.text ?? '').replaceAll(CHILD_SYMBOL, ' ') : '',
- )
- .join(CHILD_SYMBOL)
-}
-
-function diffText(
- current: string,
- next: string,
-): {patches: Patch[]; levenshtein: number} {
- const diff = makeDiff(current, next)
- const diffs = cleanupEfficiency(diff)
- return {
- patches: makePatches(current, diffs, {margin: DMP_MARGIN}),
- levenshtein: diffsLevenshtein(diffs),
- }
-}
-
-function diffApply(current: string, patches: Patch[]): string {
- return applyPatches(patches, current, {
- allowExceedingIndices: true,
- margin: DMP_MARGIN,
- })[0]
-}
-
-/**
- * Finds each stored anchor in the current editor value.
- *
- * A direct port of the Studio's `buildRangeDecorationSelectionsFromComments`,
- * minus its Studio-only inputs. The stored text is diffed against the block's
- * current text, so an anchor survives edits around it and inside it up to a
- * similarity threshold. An anchor whose text is gone, or changed beyond
- * recognition, is dropped rather than drawn somewhere wrong.
- *
- * Live tracking while the user types is not this function's job: the editor's
- * `RangeDecoration.onMoved` does that. This runs when comments load or change.
- */
-export function resolveCommentSelections(
- options: ResolveOptions,
-): AnchoredComment[] {
- const {value, comments} = options
- const anchored: AnchoredComment[] = []
-
- for (const {commentId, relativePath, selection} of comments) {
- for (const selectionMember of selection.value) {
- const container =
- relativePath.length > 0 ? getValueAtPath(value, relativePath) : value
- const matchedBlock = Array.isArray(container)
- ? container.find(
- (block) =>
- isTextBlock(block) && block._key === selectionMember._key,
- )
- : undefined
- if (!matchedBlock || !isTextBlock(matchedBlock)) {
- continue
- }
-
- const selectionText = selectionMember.text.replaceAll(
- COMMENT_INDICATORS_REGEX,
- '',
- )
- const textWithChildSeparators =
- toPlainTextWithChildSeparators(matchedBlock)
- const {patches} = diffText(selectionText, selectionMember.text)
- const diffedText = diffApply(textWithChildSeparators, patches)
- const startIndex = diffedText.indexOf(COMMENT_INDICATORS[0])
- const endIndex = diffedText
- .replaceAll(COMMENT_INDICATORS[0], '')
- .indexOf(COMMENT_INDICATORS[1])
- const textWithoutCommentTags = diffedText.replaceAll(
- COMMENT_INDICATORS_REGEX,
- '',
- )
-
- if (startIndex === -1 || endIndex === -1) {
- continue
- }
-
- const oldCommentedText = selectionMember.text.slice(
- selectionMember.text.indexOf(COMMENT_INDICATORS[0]) + 1,
- selectionMember.text.indexOf(COMMENT_INDICATORS[1]),
- )
- const newCommentedText = textWithoutCommentTags.slice(
- startIndex,
- endIndex,
- )
- const {levenshtein} = diffText(newCommentedText, oldCommentedText)
- // Kept from the Studio, oddity included: only the *old* length is halved.
- const threshold = Math.round(
- newCommentedText.length + oldCommentedText.length / 2,
- )
-
- // The anchor is lost when its text is gone or no longer recognisable.
- // Better no highlight than a highlight on the wrong words.
- if (
- newCommentedText.length === 0 ||
- levenshtein > threshold ||
- startIndex + 1 === endIndex
- ) {
- continue
- }
-
- let childIndexAnchor = 0
- let anchorOffset = 0
- let childIndexFocus = 0
- let focusOffset = 0
- for (let i = 0; i < textWithoutCommentTags.length; i++) {
- if (textWithoutCommentTags[i] === CHILD_SYMBOL) {
- if (i <= startIndex) {
- anchorOffset = -1
- childIndexAnchor++
- }
- focusOffset = -1
- childIndexFocus++
- }
- if (i < startIndex) {
- anchorOffset++
- }
- if (i < startIndex + newCommentedText.length) {
- focusOffset++
- }
- if (i === startIndex + newCommentedText.length) {
- break
- }
- }
-
- anchored.push({
- commentId,
- selection: {
- anchor: {
- path: [
- ...relativePath,
- {_key: matchedBlock._key},
- 'children',
- {_key: matchedBlock.children[childIndexAnchor]._key},
- ],
- offset: anchorOffset,
- },
- focus: {
- path: [
- ...relativePath,
- {_key: matchedBlock._key},
- 'children',
- {_key: matchedBlock.children[childIndexFocus]._key},
- ],
- offset: focusOffset,
- },
- },
- })
- }
- }
-
- return anchored
-}
-
-function diffsLevenshtein(diffs: Diff[]): number {
- let levenshtein = 0
- let insertions = 0
- let deletions = 0
- for (const [op, data] of diffs) {
- switch (op) {
- case DIFF_INSERT:
- insertions += data.length
- break
- case DIFF_DELETE:
- deletions += data.length
- break
- case DIFF_EQUAL:
- // A deletion and an insertion together count as one substitution.
- levenshtein += Math.max(insertions, deletions)
- insertions = 0
- deletions = 0
- break
- default:
- break
- }
- }
- levenshtein += Math.max(insertions, deletions)
- return levenshtein
-}
-
-/**
- * Reduces a comment's stored field path to a path inside this editor.
- *
- * `undefined` means the comment belongs to some other editor: a different
- * field, a sibling container, or a stored path that does not parse. Skipping
- * those is what lets several editors on one document each decorate only their
- * own comments.
- */
-export function relativeCommentPath(
- basePath: Path,
- fieldPath: string,
-): Path | undefined {
- let parsed: Path
- try {
- parsed = arrayifyPath(fieldPath)
- } catch {
- return undefined
- }
- if (parsed.length < basePath.length) {
- return undefined
- }
- if (!isEqualPaths(basePath, parsed.slice(0, basePath.length))) {
- return undefined
- }
- return parsed.slice(basePath.length)
-}
diff --git a/packages/plugin-sdk-value/src/comments-selection.test.ts b/packages/plugin-sdk-value/src/comments-selection.test.ts
deleted file mode 100644
index d594e85338..0000000000
--- a/packages/plugin-sdk-value/src/comments-selection.test.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import {describe, expect, test} from 'vitest'
-import {
- COMMENT_INDICATORS,
- resolveCommentSelections,
-} from './comments-anchoring'
-import {buildStoredSelection} from './comments-selection'
-
-const [START, END] = COMMENT_INDICATORS
-
-function span(_key: string, text: string) {
- return {_type: 'span', _key, marks: [], text}
-}
-
-function block(_key: string, children: ReturnType[]) {
- return {_key, _type: 'block', style: 'normal', markDefs: [], children}
-}
-
-function point(blockKey: string, spanKey: string, offset: number) {
- return {path: [{_key: blockKey}, 'children', {_key: spanKey}], offset}
-}
-
-describe(buildStoredSelection.name, () => {
- test('marks the selected run inside a single span', () => {
- const foo = block('b1', [span('s1', 'foo bar baz')])
-
- expect(
- buildStoredSelection({
- selection: {anchor: point('b1', 's1', 4), focus: point('b1', 's1', 7)},
- selectedBlocks: [{node: foo, path: [{_key: 'b1'}]}],
- }),
- ).toEqual({
- containerPath: [],
- selection: {
- type: 'text',
- value: [{_key: 'b1', text: `foo ${START}bar${END} baz`}],
- },
- })
- })
-
- test('a backward selection marks the same run', () => {
- const foo = block('b1', [span('s1', 'foo bar baz')])
-
- expect(
- buildStoredSelection({
- selection: {
- anchor: point('b1', 's1', 7),
- focus: point('b1', 's1', 4),
- backward: true,
- },
- selectedBlocks: [{node: foo, path: [{_key: 'b1'}]}],
- }),
- ).toEqual({
- containerPath: [],
- selection: {
- type: 'text',
- value: [{_key: 'b1', text: `foo ${START}bar${END} baz`}],
- },
- })
- })
-
- test('offsets count across earlier spans in the block', () => {
- const foo = block('b1', [span('s1', 'foo '), span('s2', 'bar baz')])
-
- expect(
- buildStoredSelection({
- selection: {anchor: point('b1', 's2', 0), focus: point('b1', 's2', 3)},
- selectedBlocks: [{node: foo, path: [{_key: 'b1'}]}],
- })?.selection.value,
- ).toEqual([{_key: 'b1', text: `foo ${START}bar${END} baz`}])
- })
-
- test('a selection spanning blocks marks each block, middle blocks whole', () => {
- const first = block('b1', [span('s1', 'foo bar')])
- const middle = block('b2', [span('s2', 'baz')])
- const last = block('b3', [span('s3', 'qux quux')])
-
- expect(
- buildStoredSelection({
- selection: {anchor: point('b1', 's1', 4), focus: point('b3', 's3', 3)},
- selectedBlocks: [
- {node: first, path: [{_key: 'b1'}]},
- {node: middle, path: [{_key: 'b2'}]},
- {node: last, path: [{_key: 'b3'}]},
- ],
- })?.selection.value,
- ).toEqual([
- {_key: 'b1', text: `foo ${START}bar${END}`},
- {_key: 'b2', text: `${START}baz${END}`},
- {_key: 'b3', text: `${START}qux${END} quux`},
- ])
- })
-
- test('nested blocks report their containing array', () => {
- const nested = block('b1', [span('s1', 'foo bar')])
- const path = [{_key: 'callout'}, 'content', {_key: 'b1'}]
-
- expect(
- buildStoredSelection({
- selection: {
- anchor: {
- path: [...path.slice(0, 2), {_key: 'b1'}, 'children', {_key: 's1'}],
- offset: 0,
- },
- focus: {
- path: [...path.slice(0, 2), {_key: 'b1'}, 'children', {_key: 's1'}],
- offset: 3,
- },
- },
- selectedBlocks: [{node: nested, path}],
- })?.containerPath,
- ).toEqual([{_key: 'callout'}, 'content'])
- })
-
- test('blocks from different containers refuse to build', () => {
- const topLevel = block('b1', [span('s1', 'foo')])
- const nested = block('b2', [span('s2', 'bar')])
-
- expect(
- buildStoredSelection({
- selection: {anchor: point('b1', 's1', 0), focus: point('b2', 's2', 3)},
- selectedBlocks: [
- {node: topLevel, path: [{_key: 'b1'}]},
- {node: nested, path: [{_key: 'callout'}, 'content', {_key: 'b2'}]},
- ],
- }),
- ).toBe(null)
- })
-
- test('a collapsed selection refuses to build', () => {
- const foo = block('b1', [span('s1', 'foo bar')])
-
- expect(
- buildStoredSelection({
- selection: {anchor: point('b1', 's1', 4), focus: point('b1', 's1', 4)},
- selectedBlocks: [{node: foo, path: [{_key: 'b1'}]}],
- }),
- ).toBe(null)
- })
-
- test('a null selection refuses to build', () => {
- expect(buildStoredSelection({selection: null, selectedBlocks: []})).toBe(
- null,
- )
- })
-
- test('what it writes, the reader finds again', () => {
- // The round trip is the point of matching the Studio's format: written
- // here, resolved by the same code path that resolves Studio comments.
- const foo = block('b1', [span('s1', 'foo bar baz')])
- const built = buildStoredSelection({
- selection: {anchor: point('b1', 's1', 4), focus: point('b1', 's1', 7)},
- selectedBlocks: [{node: foo, path: [{_key: 'b1'}]}],
- })
-
- const anchored = resolveCommentSelections({
- value: [foo],
- comments: [
- {
- commentId: 'c1',
- relativePath: built!.containerPath,
- selection: built!.selection,
- },
- ],
- })
-
- expect(anchored.map((a) => a.selection)).toEqual([
- {
- anchor: {offset: 4, path: [{_key: 'b1'}, 'children', {_key: 's1'}]},
- focus: {offset: 7, path: [{_key: 'b1'}, 'children', {_key: 's1'}]},
- },
- ])
- })
-})
diff --git a/packages/plugin-sdk-value/src/comments-selection.ts b/packages/plugin-sdk-value/src/comments-selection.ts
deleted file mode 100644
index b35f839ab3..0000000000
--- a/packages/plugin-sdk-value/src/comments-selection.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import type {EditorSelection} from '@portabletext/editor'
-import {isEqualPaths, isKeyedSegment} from '@portabletext/editor/utils'
-import type {Path} from '@portabletext/patches'
-import {
- COMMENT_INDICATORS,
- type StoredTextSelection,
-} from './comments-anchoring'
-
-interface SpanLike {
- _key: string
- _type: string
- text?: string
-}
-
-interface TextBlockLike {
- _key: string
- children: SpanLike[]
-}
-
-export interface SelectedTextBlock {
- node: TextBlockLike
- path: Path
-}
-
-export interface BuiltSelection {
- /**
- * The path of the array holding the selected blocks, relative to the editor.
- * Empty for blocks at the top level. Comments anchor on the containing array,
- * matching what the Studio stores.
- */
- containerPath: Path
- /** The anchor in the Studio's stored shape, ready to pass to `createComment`. */
- selection: StoredTextSelection
-}
-
-/**
- * Turns the current editor selection into the stored comment anchor.
- *
- * Per selected block, the block's entire plain text with the selection
- * boundaries marked by the two indicator characters. The write-time mirror of
- * `resolveCommentSelections`, and deliberately built the way the Studio builds
- * it so a comment written here re-anchors there and back.
- *
- * Returns `null` when there is nothing commentable: a collapsed selection,
- * no selected text, or a selection spanning blocks from different containing
- * arrays, which a single stored path cannot describe.
- */
-export function buildStoredSelection(options: {
- selection: EditorSelection
- selectedBlocks: SelectedTextBlock[]
-}): BuiltSelection | null {
- const {selection, selectedBlocks} = options
- if (!selection || selectedBlocks.length === 0) {
- return null
- }
-
- const [start, end] = selection.backward
- ? [selection.focus, selection.anchor]
- : [selection.anchor, selection.focus]
-
- const containerPath = selectedBlocks[0].path.slice(0, -1)
- const sharedContainer = selectedBlocks.every((selected) =>
- isEqualPaths(selected.path.slice(0, -1), containerPath),
- )
- if (!sharedContainer) {
- return null
- }
-
- let selectedCharacters = 0
- const value = selectedBlocks.map((selected, index) => {
- const isFirst = index === 0
- const isLast = index === selectedBlocks.length - 1
- const plain = plainText(selected.node)
-
- const from = isFirst
- ? plainOffset(selected.node, start.path, start.offset)
- : 0
- const to = isLast
- ? plainOffset(selected.node, end.path, end.offset)
- : plain.length
-
- selectedCharacters += Math.max(0, to - from)
-
- return {
- _key: selected.node._key,
- text: `${plain.slice(0, from)}${COMMENT_INDICATORS[0]}${plain.slice(from, to)}${COMMENT_INDICATORS[1]}${plain.slice(to)}`,
- }
- })
-
- // A collapsed selection, or one that only touches empty text, anchors to
- // nothing worth highlighting.
- if (selectedCharacters === 0) {
- return null
- }
-
- return {containerPath, selection: {type: 'text', value}}
-}
-
-function plainText(block: TextBlockLike): string {
- return block.children
- .map((child) => (isSpan(child) ? (child.text ?? '') : ''))
- .join('')
-}
-
-/**
- * Converts a selection point into an offset within the block's plain text: the
- * text of every span before the point's child, plus the offset inside it. A
- * point whose child is not in this block clamps to the block edge, which is
- * where a cross-block selection boundary lands.
- */
-function plainOffset(
- block: TextBlockLike,
- pointPath: Path,
- offset: number,
-): number {
- const childSegment = pointPath[pointPath.length - 1]
- if (!isKeyedSegment(childSegment)) {
- return offset
- }
-
- let total = 0
- for (const child of block.children) {
- if (child._key === childSegment._key) {
- return total + (isSpan(child) ? offset : 0)
- }
- if (isSpan(child)) {
- total += (child.text ?? '').length
- }
- }
- return total
-}
-
-function isSpan(child: SpanLike): boolean {
- return child._type === 'span' && typeof child.text === 'string'
-}
diff --git a/packages/plugin-sdk-value/src/debug.ts b/packages/plugin-sdk-value/src/debug.ts
deleted file mode 100644
index 3fd370a3af..0000000000
--- a/packages/plugin-sdk-value/src/debug.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import {createDebug, enabled} from 'obug'
-
-// Keep in sync with `packages/editor/src/internal-utils/debug.ts`: sharing
-// the `pte:` root lets `localStorage.debug = 'pte:*'` interleave this
-// plugin's sync traces with the editor's own output on one timeline.
-const rootName = 'pte:plugin-sdk-value:'
-
-function createDebugger(name: string) {
- const namespace = `${rootName}${name}`
- if (enabled(namespace)) {
- return createDebug(namespace)
- }
- return createDebug(rootName)
-}
-
-export const debug = {
- mutation: createDebugger('mutation'),
- push: createDebugger('push'),
- remote: createDebugger('remote'),
- repair: createDebugger('repair'),
-}
diff --git a/packages/plugin-sdk-value/src/index.ts b/packages/plugin-sdk-value/src/index.ts
deleted file mode 100644
index 19f1002da4..0000000000
--- a/packages/plugin-sdk-value/src/index.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-export {
- SDKPresencePlugin,
- useSDKPresenceCursors,
- type RenderCursorFunction,
- type SDKPresencePluginProps,
- type SDKRemoteCursor,
- type UseSDKPresenceCursorsOptions,
-} from './plugin.sdk-presence'
-export {
- useSDKCommentAuthoring,
- useSDKCommentDecorations,
- type RenderCommentDecorationFunction,
- type SDKCommentAuthoring,
- type UseSDKCommentAuthoringOptions,
- type UseSDKCommentDecorationsOptions,
-} from './plugin.sdk-comments'
-export {SDKValuePlugin, ValueSyncPlugin} from './plugin.sdk-value'
-export {
- SDKPortableTextEditable,
- type SDKPortableTextEditableProps,
-} from './sdk-editable'
diff --git a/packages/plugin-sdk-value/src/plugin.collision-matrix.test.tsx b/packages/plugin-sdk-value/src/plugin.collision-matrix.test.tsx
deleted file mode 100644
index 322a9b6b19..0000000000
--- a/packages/plugin-sdk-value/src/plugin.collision-matrix.test.tsx
+++ /dev/null
@@ -1,932 +0,0 @@
-import type {
- Editor,
- EditorSelection,
- Patch as PtePatch,
-} from '@portabletext/editor'
-import {EditorProvider, PortableTextEditable} from '@portabletext/editor'
-import {EditorRefPlugin} from '@portabletext/editor/plugins'
-import {defineSchema, type PortableTextBlock} from '@portabletext/schema'
-import {diffValue, type SanityPatchOperations} from '@sanity/diff-patch'
-import {createRef} from 'react'
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest'
-import {render} from 'vitest-browser-react'
-import {page} from 'vitest/browser'
-import {
- convertPatchesToSanity,
- scopeRemotePatches,
- ValueSyncPlugin,
-} from './plugin.sdk-value'
-import {
- applyPatchOperations,
- type SanityPatchOperationRecord,
-} from './test/apply-sanity-patch-operations'
-
-/**
- * Deterministic collision matrix: two live editors connected through a mock
- * server that applies real Sanity patch operations with Content Lake
- * semantics. Each scenario fires one concurrent edit per client, then the
- * server delivers the colliding transactions in both orders (A first, B
- * first).
- *
- * Every scenario asserts the hard safety invariants:
- * - both editors converge on the server value (no frozen/diverged tabs)
- * - the server value is valid Portable Text (no orphan marks, no spans
- * with children, no inline link objects)
- * - `kind: 'type'` scenarios also assert both clients' typed markers
- * survive (the silent-loss axis)
- *
- * The scenarios mirror the Playwright concurrency harness
- * (sanity-labs/pte-sdk-concurrent-repro) so regressions the harness would
- * catch fail here first, deterministically and offline.
- */
-
-const FIELD = 'content'
-
-// ---------------------------------------------------------------------------
-// Mock server with Content Lake patch semantics
-// ---------------------------------------------------------------------------
-
-function createContentLakeServer(initialBlocks: PortableTextBlock[]) {
- let serverDocument: unknown = {[FIELD]: initialBlocks}
-
- type Transaction = {ops: SanityPatchOperations[]}
-
- type ClientChannels = {
- pending: Transaction[]
- valueSubscriber: (() => void) | null
- patchSubscriber: ((patches: PtePatch[]) => void) | null
- }
-
- const clients: [ClientChannels, ClientChannels] = [
- {pending: [], valueSubscriber: null, patchSubscriber: null},
- {pending: [], valueSubscriber: null, patchSubscriber: null},
- ]
-
- const deliveries: Array<{client: 0 | 1; run: () => void}> = []
-
- function applyTransaction(doc: unknown, transaction: Transaction): unknown {
- return transaction.ops.reduce(
- (acc, ops) =>
- applyPatchOperations(acc, ops as SanityPatchOperationRecord),
- doc,
- )
- }
-
- // A client's local document is the server truth with its own
- // unacknowledged transactions rebased on top, like the SDK's optimistic
- // document store. Transactions that fail to apply revert.
- function localDocument(client: ClientChannels): unknown {
- return client.pending.reduce((doc, transaction) => {
- try {
- return applyTransaction(doc, transaction)
- } catch {
- return doc
- }
- }, serverDocument)
- }
-
- function fieldValue(doc: unknown): PortableTextBlock[] {
- return (doc as {[key: string]: PortableTextBlock[]})[FIELD]
- }
-
- function queueTransaction(index: 0 | 1, ops: SanityPatchOperations[]) {
- const client = clients[index]
- const other = clients[index === 0 ? 1 : 0]
- const transaction: Transaction = {ops}
- client.pending.push(transaction)
- client.valueSubscriber?.()
-
- deliveries.push({
- client: index,
- run: () => {
- let applied: unknown
- try {
- applied = applyTransaction(serverDocument, transaction)
- } catch {
- // content lake rejects the whole transaction; the SDK reverts it
- client.pending.splice(client.pending.indexOf(transaction), 1)
- client.valueSubscriber?.()
- return
- }
- serverDocument = applied
- client.pending.splice(client.pending.indexOf(transaction), 1)
-
- // the listener echoes the transaction to the other client: the SDK
- // extracts the patch operations into a `remote-patches` event (which
- // the plugin scopes to the field) and updates its document state
- let ptePatches: PtePatch[] | null
- try {
- ptePatches = scopeRemotePatches(transaction.ops, FIELD)
- } catch {
- ptePatches = null
- }
- if (ptePatches && ptePatches.length > 0) {
- other.patchSubscriber?.(ptePatches)
- }
- other.valueSubscriber?.()
- client.valueSubscriber?.()
- },
- })
- }
-
- function createStore(index: 0 | 1) {
- const client = clients[index]
- return {
- getRemoteValue: () => fieldValue(localDocument(client)),
- onRemoteValueChange: (callback: () => void) => {
- client.valueSubscriber = callback
- return () => {
- client.valueSubscriber = null
- }
- },
- onRemotePatches: (callback: (patches: PtePatch[]) => void) => {
- client.patchSubscriber = callback
- return () => {
- client.patchSubscriber = null
- }
- },
- // the whole-value fallback: the SDK diffs the new field value against
- // the client's local document, producing granular operations
- pushValue: vi.fn((newValue: PortableTextBlock[]) => {
- const doc = localDocument(client)
- const ops = diffValue(doc, {
- ...(doc as {[key: string]: unknown}),
- [FIELD]: newValue,
- })
- if (ops.length > 0) {
- queueTransaction(index, ops)
- }
- }),
- // the patch channel: editor patches convert to Sanity operations
- // rooted at the field; a conversion error propagates so the plugin
- // falls back to pushing the whole value
- pushPatches: vi.fn((patches: PtePatch[]) => {
- queueTransaction(
- index,
- convertPatchesToSanity(patches, {
- prefix: FIELD,
- }) as SanityPatchOperations[],
- )
- }),
- }
- }
-
- return {
- storeA: createStore(0),
- storeB: createStore(1),
- getServerValue: () => fieldValue(serverDocument),
- hasPendingDeliveries: () => deliveries.length > 0,
- deliverClient: (index: 0 | 1) => {
- // deliver the transactions this client has queued so far, in order
- const queued = deliveries.filter((entry) => entry.client === index)
- for (const entry of queued) {
- deliveries.splice(deliveries.indexOf(entry), 1)
- entry.run()
- }
- },
- deliverAll: () => {
- while (deliveries.length > 0) {
- deliveries.shift()!.run()
- }
- },
- }
-}
-
-type Server = ReturnType
-type Store = Server['storeA']
-
-// ---------------------------------------------------------------------------
-// Portable Text validity (the corruption signal)
-// ---------------------------------------------------------------------------
-
-const DECORATORS = ['strong', 'em']
-
-function validatePortableText(blocks: unknown): string[] {
- const problems: string[] = []
- if (!Array.isArray(blocks)) {
- return ['value is not an array']
- }
- for (const block of blocks as Array<{
- _type?: string
- markDefs?: Array<{_key?: string; _type?: string}>
- children?: Array<{
- _type?: string
- children?: unknown
- marks?: string[]
- }>
- }>) {
- if (!block || typeof block !== 'object') {
- problems.push('non-object block')
- continue
- }
- if (block._type !== 'block') {
- continue
- }
- const markDefKeys = new Set(
- (block.markDefs ?? []).map((def) => def && def._key),
- )
- for (const def of block.markDefs ?? []) {
- if (def && def._type && def._type !== 'link') {
- problems.push(`markDef _type "${def._type}" (expected link)`)
- }
- }
- for (const child of block.children ?? []) {
- if (!child || typeof child !== 'object') {
- problems.push('non-object child')
- continue
- }
- if (child._type === 'link') {
- problems.push('inline _type:"link" child')
- }
- if (child._type === 'span') {
- if (Array.isArray(child.children)) {
- problems.push('span has children[]')
- }
- for (const mark of child.marks ?? []) {
- if (!DECORATORS.includes(mark) && !markDefKeys.has(mark)) {
- problems.push(`orphan mark "${mark}" (no markDef)`)
- }
- }
- }
- }
- }
- return [...new Set(problems)]
-}
-
-function textOf(blocks: PortableTextBlock[] | undefined): string {
- return (blocks ?? [])
- .map((block) =>
- Array.isArray((block as {children?: unknown}).children)
- ? (block as {children: Array<{text?: string}>}).children
- .map((child) => child.text ?? '')
- .join('')
- : '',
- )
- .join('\n')
-}
-
-// ---------------------------------------------------------------------------
-// Selection helpers (offsets survive span splits by walking children)
-// ---------------------------------------------------------------------------
-
-function blockAt(
- editor: Editor,
- index: number,
-): {_key: string; children: Array<{_key: string; text?: string}>} | undefined {
- const value = editor.getSnapshot().context.value
- if (!Array.isArray(value) || value.length <= index) {
- return undefined
- }
- const block = value[index] as unknown as {
- _key: string
- children?: Array<{_key: string; text?: string}>
- }
- if (!block || !Array.isArray(block.children) || block.children.length === 0) {
- return undefined
- }
- return block as {_key: string; children: Array<{_key: string; text?: string}>}
-}
-
-function pointInBlock(
- block: {children: Array<{_key: string; text?: string}>},
- globalOffset: number,
-): {key: string; offset: number} {
- let acc = 0
- for (const child of block.children) {
- const length = (child.text ?? '').length
- if (globalOffset <= acc + length) {
- return {key: child._key, offset: globalOffset - acc}
- }
- acc += length
- }
- const last = block.children[block.children.length - 1]
- return {key: last._key, offset: (last.text ?? '').length}
-}
-
-function rangeInBlock(
- editor: Editor,
- blockIndex: number,
- from: number,
- to: number,
-): EditorSelection {
- const block = blockAt(editor, blockIndex)
- if (!block) {
- return null
- }
- const anchor = pointInBlock(block, from)
- const focus = pointInBlock(block, to)
- return {
- anchor: {
- path: [{_key: block._key}, 'children', {_key: anchor.key}],
- offset: anchor.offset,
- },
- focus: {
- path: [{_key: block._key}, 'children', {_key: focus.key}],
- offset: focus.offset,
- },
- }
-}
-
-function caretInBlock(
- editor: Editor,
- blockIndex: number,
- offset: number,
-): EditorSelection {
- return rangeInBlock(editor, blockIndex, offset, offset)
-}
-
-function caretAtBlockEnd(editor: Editor, blockIndex: number): EditorSelection {
- const block = blockAt(editor, blockIndex)
- if (!block) {
- return null
- }
- const length = block.children.reduce(
- (sum, child) => sum + (child.text ?? '').length,
- 0,
- )
- return caretInBlock(editor, blockIndex, length)
-}
-
-function typeAt(editor: Editor, at: EditorSelection, text: string) {
- if (!at) {
- return
- }
- editor.send({type: 'select', at})
- editor.send({type: 'insert.text', text})
-}
-
-// ---------------------------------------------------------------------------
-// Seeds
-// ---------------------------------------------------------------------------
-
-const seedSingle = (): PortableTextBlock[] => [
- {
- _type: 'block',
- _key: 'b1',
- style: 'normal',
- markDefs: [],
- children: [
- {
- _type: 'span',
- _key: 's1',
- text: 'The quick brown fox jumps over the lazy dog',
- marks: [],
- },
- ],
- },
-]
-
-const seedTwoBlocks = (): PortableTextBlock[] => [
- ...seedSingle(),
- {
- _type: 'block',
- _key: 'b2',
- style: 'normal',
- markDefs: [],
- children: [
- {
- _type: 'span',
- _key: 's3',
- text: 'Pack my box with five dozen liquor jugs',
- marks: [],
- },
- ],
- },
-]
-
-// two spans with different marks so normalization keeps them separate
-const seedTwoSpans = (): PortableTextBlock[] => [
- {
- _type: 'block',
- _key: 'b1',
- style: 'normal',
- markDefs: [],
- children: [
- {
- _type: 'span',
- _key: 's1',
- text: 'The quick brown fox ',
- marks: ['strong'],
- },
- {
- _type: 'span',
- _key: 's2',
- text: 'jumps over the lazy dog',
- marks: [],
- },
- ],
- },
-]
-
-// ---------------------------------------------------------------------------
-// Scenarios (ported from the Playwright harness)
-// ---------------------------------------------------------------------------
-
-const MARK_A = '{A}0'
-const MARK_B = '{B}0'
-
-type Role = 'A' | 'B'
-
-interface CollisionScenario {
- id: string
- title: string
- kind: 'type' | 'format'
- seed: () => PortableTextBlock[]
- markers?: Partial>
- run: (editor: Editor, role: Role) => void
-}
-
-const SCENARIOS: CollisionScenario[] = [
- {
- id: 'disjoint-blocks',
- title: 'typing in different blocks',
- kind: 'type',
- seed: seedTwoBlocks,
- markers: {A: MARK_A, B: MARK_B},
- run: (editor, role) => {
- const blockIndex = role === 'A' ? 0 : 1
- const marker = role === 'A' ? MARK_A : MARK_B
- typeAt(editor, caretAtBlockEnd(editor, blockIndex), ` ${marker}`)
- },
- },
- {
- id: 'disjoint-spans',
- title: 'typing in different spans of the same block',
- kind: 'type',
- seed: seedTwoSpans,
- markers: {A: MARK_A, B: MARK_B},
- run: (editor, role) => {
- if (role === 'A') {
- typeAt(editor, caretInBlock(editor, 0, 4), MARK_A)
- } else {
- typeAt(editor, caretAtBlockEnd(editor, 0), MARK_B)
- }
- },
- },
- {
- id: 'same-span-ends',
- title: 'typing at both ends of the same span',
- kind: 'type',
- seed: seedSingle,
- markers: {A: MARK_A, B: MARK_B},
- run: (editor, role) => {
- if (role === 'A') {
- typeAt(editor, caretInBlock(editor, 0, 0), MARK_A)
- } else {
- typeAt(editor, caretAtBlockEnd(editor, 0), MARK_B)
- }
- },
- },
- {
- id: 'same-caret',
- title: 'typing at the same caret',
- kind: 'type',
- seed: seedSingle,
- markers: {A: MARK_A, B: MARK_B},
- run: (editor, role) => {
- const marker = role === 'A' ? MARK_A : MARK_B
- typeAt(editor, caretInBlock(editor, 0, 4), marker)
- },
- },
- {
- id: 'bold-same-range',
- title: 'bolding the same range',
- kind: 'format',
- seed: seedSingle,
- run: (editor) => {
- const at = rangeInBlock(editor, 0, 0, 9)
- if (!at) {
- return
- }
- editor.send({type: 'select', at})
- editor.send({type: 'decorator.toggle', decorator: 'strong', at})
- },
- },
- {
- id: 'bold-overlap-range',
- title: 'bolding overlapping ranges',
- kind: 'format',
- seed: seedSingle,
- run: (editor, role) => {
- const at =
- role === 'A'
- ? rangeInBlock(editor, 0, 0, 15)
- : rangeInBlock(editor, 0, 8, 25)
- if (!at) {
- return
- }
- editor.send({type: 'select', at})
- editor.send({type: 'decorator.toggle', decorator: 'strong', at})
- },
- },
- {
- id: 'link-same-range',
- title: 'linking the same range',
- kind: 'format',
- seed: seedSingle,
- run: (editor, role) => {
- const at = rangeInBlock(editor, 0, 0, 9)
- if (!at) {
- return
- }
- editor.send({type: 'select', at})
- editor.send({
- type: 'annotation.toggle',
- annotation: {
- name: 'link',
- value: {href: `https://${role.toLowerCase()}.example/`},
- },
- at,
- })
- },
- },
- {
- id: 'link-overlap-range',
- title: 'linking overlapping ranges',
- kind: 'format',
- seed: seedSingle,
- run: (editor, role) => {
- const at =
- role === 'A'
- ? rangeInBlock(editor, 0, 0, 15)
- : rangeInBlock(editor, 0, 8, 25)
- if (!at) {
- return
- }
- editor.send({type: 'select', at})
- editor.send({
- type: 'annotation.toggle',
- annotation: {
- name: 'link',
- value: {href: `https://${role.toLowerCase()}.example/`},
- },
- at,
- })
- },
- },
- {
- id: 'block-split',
- title: 'concurrent block split (Enter at different offsets)',
- kind: 'format',
- seed: seedSingle,
- run: (editor, role) => {
- const at =
- role === 'A' ? caretInBlock(editor, 0, 10) : caretInBlock(editor, 0, 25)
- if (!at) {
- return
- }
- editor.send({type: 'select', at})
- editor.send({type: 'insert.break'})
- },
- },
- {
- id: 'delete-overlap',
- title: 'deleting overlapping ranges',
- kind: 'format',
- seed: seedSingle,
- run: (editor, role) => {
- const at =
- role === 'A'
- ? rangeInBlock(editor, 0, 0, 15)
- : rangeInBlock(editor, 0, 8, 25)
- if (!at) {
- return
- }
- editor.send({type: 'select', at})
- editor.send({type: 'delete', at})
- },
- },
- {
- id: 'format-vs-type',
- title: 'formatting while the other client types in the same span',
- kind: 'type',
- seed: seedSingle,
- markers: {B: MARK_B},
- run: (editor, role) => {
- if (role === 'A') {
- const at = rangeInBlock(editor, 0, 0, 9)
- if (!at) {
- return
- }
- editor.send({type: 'select', at})
- editor.send({type: 'decorator.toggle', decorator: 'strong', at})
- } else {
- typeAt(editor, caretAtBlockEnd(editor, 0), ` ${MARK_B}`)
- }
- },
- },
- {
- id: 'disjoint-blocks-format',
- title: 'formatting in different blocks',
- kind: 'format',
- seed: seedTwoBlocks,
- run: (editor, role) => {
- const blockIndex = role === 'A' ? 0 : 1
- const at = rangeInBlock(editor, blockIndex, 0, 9)
- if (!at) {
- return
- }
- editor.send({type: 'select', at})
- editor.send({type: 'decorator.toggle', decorator: 'strong', at})
- },
- },
-]
-
-// ---------------------------------------------------------------------------
-// Rig
-// ---------------------------------------------------------------------------
-
-const schemaDefinition = defineSchema({
- decorators: [{name: 'strong'}, {name: 'em'}],
- annotations: [{name: 'link', fields: [{name: 'href', type: 'string'}]}],
-})
-
-async function renderTwoClients(server: Server) {
- const editorARef = createRef()
- const editorBRef = createRef()
-
- const client = (ref: React.Ref, store: Store, testId: string) => (
-
-
-
-
-
- )
-
- const result = await render(
- <>
- {client(editorARef, server.storeA, 'client-a')}
- {client(editorBRef, server.storeB, 'client-b')}
- >,
- )
-
- await vi.waitFor(() => {
- expect(editorARef.current).toBeTruthy()
- expect(editorBRef.current).toBeTruthy()
- })
-
- return {
- editorA: editorARef.current!,
- editorB: editorBRef.current!,
- locatorA: page.getByTestId('client-a'),
- locatorB: page.getByTestId('client-b'),
- unmount: result.unmount,
- }
-}
-
-async function waitForPush(store: Store) {
- await vi.waitFor(
- () => {
- expect(
- store.pushPatches.mock.calls.length + store.pushValue.mock.calls.length,
- ).toBeGreaterThan(0)
- },
- {timeout: 5000, interval: 50},
- )
-}
-
-async function collideAndSettle(options: {
- server: Server
- editorA: Editor
- editorB: Editor
- first: 0 | 1
-}) {
- const {server, editorA, editorB, first} = options
-
- // deliver the colliding transactions in the enumerated order, then let
- // repair pushes drain first-in-first-out until everything converges
- server.deliverClient(first)
- server.deliverClient(first === 0 ? 1 : 0)
-
- await vi.waitFor(
- () => {
- server.deliverAll()
- expect(server.hasPendingDeliveries()).toBe(false)
- expect(editorA.getSnapshot().context.value).toEqual(
- server.getServerValue(),
- )
- expect(editorB.getSnapshot().context.value).toEqual(
- server.getServerValue(),
- )
- },
- {timeout: 10000, interval: 100},
- )
-}
-
-// ---------------------------------------------------------------------------
-// The matrix
-// ---------------------------------------------------------------------------
-
-/**
- * Known limitation, not a regression gate: when a client's span split
- * (formatting) commits before another client's text append into the same
- * span, the append's diff-match-patch hunk no longer matches either half
- * at the server and is dropped. Recovering the text would need operational
- * rebase of the in-flight patch (what `@sanity/mutate` does in the
- * Studio). The combo must still converge to valid Portable Text; only the
- * marker-survival assertion is relaxed.
- */
-const KNOWN_MARKER_LOSS: Array<{
- scenario: string
- first: 0 | 1
- marker: Role
-}> = [{scenario: 'format-vs-type', first: 0, marker: 'B'}]
-
-describe('collision matrix', () => {
- let cleanup: (() => void) | undefined
- let consoleError: ReturnType
-
- beforeEach(() => {
- // concurrent edits legitimately log caught engine errors during the
- // divergence window; crashes surface as uncaught errors and fail the
- // test regardless
- consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
- })
-
- afterEach(() => {
- cleanup?.()
- cleanup = undefined
- consoleError.mockRestore()
- })
-
- const orderings: Array<{label: string; first: 0 | 1}> = [
- {label: 'A delivered first', first: 0},
- {label: 'B delivered first', first: 1},
- ]
-
- for (const scenario of SCENARIOS) {
- for (const ordering of orderings) {
- test(`Scenario: ${scenario.title} settles into valid content (${scenario.id}, ${ordering.label})`, async () => {
- const server = createContentLakeServer(scenario.seed())
- const {editorA, editorB, locatorA, locatorB, unmount} =
- await renderTwoClients(server)
- cleanup = unmount
-
- await locatorA.click()
- scenario.run(editorA, 'A')
- await locatorB.click()
- scenario.run(editorB, 'B')
-
- await waitForPush(server.storeA)
- await waitForPush(server.storeB)
-
- await collideAndSettle({
- server,
- editorA,
- editorB,
- first: ordering.first,
- })
-
- const serverBlocks = server.getServerValue()
- expect(validatePortableText(serverBlocks)).toEqual([])
-
- const isKnownLoss = (marker: Role) =>
- KNOWN_MARKER_LOSS.some(
- (entry) =>
- entry.scenario === scenario.id &&
- entry.first === ordering.first &&
- entry.marker === marker,
- )
-
- if (scenario.markers?.A && !isKnownLoss('A')) {
- expect(textOf(serverBlocks)).toContain(scenario.markers.A)
- }
- if (scenario.markers?.B && !isKnownLoss('B')) {
- expect(textOf(serverBlocks)).toContain(scenario.markers.B)
- }
- })
- }
- }
-})
-
-/**
- * Regression rig for the `annotation.remove` stack overflow: repeated rounds
- * of overlapping links with remote patches delivered between rounds, without
- * waiting for the editors to converge. Before the guard fix in
- * `preventOverlappingAnnotations`, this class of interleaving could drive an
- * editor into an unbounded remove-then-re-add raise loop that overflowed the
- * call stack and left the editor blank.
- */
-describe('multi-round link overlap', () => {
- let cleanup: (() => void) | undefined
- let consoleErrors: Array = []
- let consoleError: ReturnType
-
- beforeEach(() => {
- consoleErrors = []
- consoleError = vi
- .spyOn(console, 'error')
- .mockImplementation((...args: Array) => {
- consoleErrors.push(
- args
- .map((arg) => (arg instanceof Error ? arg.message : String(arg)))
- .join(' '),
- )
- })
- })
-
- afterEach(() => {
- cleanup?.()
- cleanup = undefined
- consoleError.mockRestore()
- })
-
- const orderings: Array<{label: string; first: 0 | 1}> = [
- {label: 'A delivered first', first: 0},
- {label: 'B delivered first', first: 1},
- ]
-
- function pushCount(store: Store) {
- return (
- store.pushPatches.mock.calls.length + store.pushValue.mock.calls.length
- )
- }
-
- async function waitForNewPush(store: Store, baseline: number) {
- await vi.waitFor(
- () => {
- expect(pushCount(store)).toBeGreaterThan(baseline)
- },
- {timeout: 5000, interval: 25},
- )
- }
-
- for (const ordering of orderings) {
- test(`Scenario: three rounds of overlapping links without convergence waits converge without a stack overflow (${ordering.label})`, async () => {
- const server = createContentLakeServer(seedSingle())
- const {editorA, editorB, locatorA, locatorB, unmount} =
- await renderTwoClients(server)
- cleanup = unmount
-
- const linkRound = (editor: Editor, role: Role) => {
- const at =
- role === 'A'
- ? rangeInBlock(editor, 0, 0, 15)
- : rangeInBlock(editor, 0, 8, 25)
- if (!at) {
- return
- }
- editor.send({type: 'select', at})
- editor.send({
- type: 'annotation.toggle',
- annotation: {
- name: 'link',
- value: {href: `https://${role.toLowerCase()}.example/`},
- },
- at,
- })
- }
-
- for (let round = 0; round < 3; round++) {
- const baselineA = pushCount(server.storeA)
- const baselineB = pushCount(server.storeB)
-
- await locatorA.click()
- linkRound(editorA, 'A')
- await locatorB.click()
- linkRound(editorB, 'B')
-
- await waitForNewPush(server.storeA, baselineA)
- await waitForNewPush(server.storeB, baselineB)
-
- // Deliver both clients' queued transactions so remote patches reach
- // the other editor mid-flight, then start the next round without
- // waiting for convergence
- server.deliverClient(ordering.first)
- server.deliverClient(ordering.first === 0 ? 1 : 0)
- }
-
- await vi.waitFor(
- () => {
- server.deliverAll()
- expect(server.hasPendingDeliveries()).toBe(false)
-
- // Upserted def inserts self-clean re-sends, so the server value
- // must be duplicate-free and the editors must mirror it exactly.
- const serverValue = server.getServerValue()
- expect(editorA.getSnapshot().context.value).toEqual(serverValue)
- expect(editorB.getSnapshot().context.value).toEqual(serverValue)
- },
- {timeout: 10000, interval: 100},
- )
-
- expect(
- consoleErrors.filter((message) =>
- message.includes('Maximum call stack'),
- ),
- ).toEqual([])
- expect(validatePortableText(server.getServerValue())).toEqual([])
- })
- }
-})
diff --git a/packages/plugin-sdk-value/src/plugin.presence-sync.test.tsx b/packages/plugin-sdk-value/src/plugin.presence-sync.test.tsx
deleted file mode 100644
index 7eaf58365c..0000000000
--- a/packages/plugin-sdk-value/src/plugin.presence-sync.test.tsx
+++ /dev/null
@@ -1,181 +0,0 @@
-import {EditorProvider, PortableTextEditable} from '@portabletext/editor'
-import {defineSchema, type PortableTextBlock} from '@portabletext/schema'
-import {useMemo, type PropsWithChildren, type ReactElement} from 'react'
-import {describe, expect, test} from 'vitest'
-import {render} from 'vitest-browser-react'
-import {page} from 'vitest/browser'
-import {useRemoteCursors} from './plugin.presence-sync'
-import {renderDefaultCursor} from './presence-caret'
-import type {RemoteCursor} from './presence-cursors'
-
-const schemaDefinition = defineSchema({
- decorators: [{name: 'strong'}],
-})
-
-const initialValue: PortableTextBlock[] = [
- {
- _type: 'block',
- _key: 'block-1',
- style: 'normal',
- markDefs: [],
- children: [{_type: 'span', _key: 'span-1', text: 'Hello world', marks: []}],
- },
-]
-
-function caretAt(offset: number): RemoteCursor['selection'] {
- const path = [{_key: 'block-1'}, 'children', {_key: 'span-1'}]
- return {anchor: {path, offset}, focus: {path, offset}}
-}
-
-function Harness(props: {
- cursors: readonly RemoteCursor[]
- useDefaultCaret?: boolean
-}) {
- const cursors = useMemo(() => props.cursors, [props.cursors])
- const rangeDecorations = useRemoteCursors({
- cursors,
- renderCursor: props.useDefaultCaret
- ? (renderDefaultCursor as (
- cursor: RemoteCursor,
- ) => (componentProps: PropsWithChildren) => ReactElement)
- : (cursor) => (componentProps: PropsWithChildren) => (
-
- {componentProps.children}
-
- ),
- })
-
- return (
-
- )
-}
-
-async function renderEditor(
- cursors: readonly RemoteCursor[],
- options: {useDefaultCaret?: boolean} = {},
-) {
- const result = await render(
-
-
- ,
- )
-
- await expect.element(page.getByTestId('editable')).toBeInTheDocument()
-
- return result
-}
-
-describe('useRemoteCursors in a real editor', () => {
- test('Scenario: a remote participant gets a caret', async () => {
- await renderEditor([{sessionId: 'session-a', selection: caretAt(5)}])
-
- await expect
- .element(page.getByTestId('caret-session-a'))
- .toBeInTheDocument()
- })
-
- test('Scenario: a participant with no selection gets no caret', async () => {
- await renderEditor([{sessionId: 'session-a', selection: null}])
-
- await expect
- .element(page.getByTestId('caret-session-a'))
- .not.toBeInTheDocument()
- })
-
- test('Scenario: two tabs of one person draw one caret per session', async () => {
- await renderEditor([
- {sessionId: 'session-a', selection: caretAt(2)},
- {sessionId: 'session-b', selection: caretAt(8)},
- ])
-
- await expect
- .element(page.getByTestId('caret-session-a'))
- .toBeInTheDocument()
- await expect
- .element(page.getByTestId('caret-session-b'))
- .toBeInTheDocument()
- })
-})
-
-function participant(
- sessionId: string,
- userId: string,
- displayName: string,
- offset: number,
-): RemoteCursor {
- return {
- sessionId,
- selection: caretAt(offset),
- user: {sanityUserId: userId, profile: {displayName}},
- } as unknown as RemoteCursor
-}
-
-function caretColorOf(sessionId: string): string {
- const element = page.getByTestId(`presence-caret-${sessionId}`).element()
- return getComputedStyle(element).borderLeftColor
-}
-
-describe('the default caret', () => {
- const cursor = participant('session-a', 'user-abc', 'Ada Lovelace', 5)
-
- test('Scenario: the default caret draws without the app providing a caret component', async () => {
- await renderEditor([cursor], {useDefaultCaret: true})
-
- await expect
- .element(page.getByTestId('presence-caret-session-a'))
- .toBeInTheDocument()
- })
-
- test('Scenario: the default caret is not editable, so the local cursor cannot land inside it', async () => {
- await renderEditor([cursor], {useDefaultCaret: true})
-
- await expect
- .element(page.getByTestId('presence-caret-session-a'))
- .toHaveAttribute('contenteditable', 'false')
- })
-
- test('Scenario: the default caret names the participant on its dot, for hover', async () => {
- await renderEditor([cursor], {useDefaultCaret: true})
-
- await expect
- .element(page.getByTestId('presence-caret-dot-session-a'))
- .toHaveAttribute('title', 'Ada Lovelace')
- })
-})
-
-describe('the default caret colour', () => {
- test('Scenario: one person in two tabs gets matching caret colours, so they read as the same user', async () => {
- await renderEditor(
- [
- participant('session-a', 'user-abc', 'Ada Lovelace', 2),
- participant('session-b', 'user-abc', 'Ada Lovelace', 8),
- ],
- {useDefaultCaret: true},
- )
-
- await expect
- .element(page.getByTestId('presence-caret-session-b'))
- .toBeInTheDocument()
-
- expect(caretColorOf('session-a')).toBe(caretColorOf('session-b'))
- })
-
- test('Scenario: two people get different caret colours, so they can be told apart', async () => {
- await renderEditor(
- [
- participant('session-a', 'user-abc', 'Ada Lovelace', 2),
- participant('session-b', 'user-xyz', 'Grace Hopper', 8),
- ],
- {useDefaultCaret: true},
- )
-
- await expect
- .element(page.getByTestId('presence-caret-session-b'))
- .toBeInTheDocument()
-
- expect(caretColorOf('session-a')).not.toBe(caretColorOf('session-b'))
- })
-})
diff --git a/packages/plugin-sdk-value/src/plugin.presence-sync.tsx b/packages/plugin-sdk-value/src/plugin.presence-sync.tsx
deleted file mode 100644
index 0366416c89..0000000000
--- a/packages/plugin-sdk-value/src/plugin.presence-sync.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-import {
- useEditor,
- useEditorSelector,
- type EditorSelection,
- type RangeDecoration,
-} from '@portabletext/editor'
-import {getSelection} from '@portabletext/editor/selectors'
-import {isEqualSelections} from '@portabletext/editor/utils'
-import {
- useCallback,
- useMemo,
- useState,
- type PropsWithChildren,
- type ReactElement,
-} from 'react'
-import {
- recordCursorMove,
- toRangeDecorations,
- type CursorOverride,
- type RemoteCursor,
-} from './presence-cursors'
-
-/**
- * Options for {@link useRemoteCursors}.
- *
- * @public
- */
-export interface UseRemoteCursorsOptions {
- /**
- * The remote participants to draw. Keep this array referentially stable, for
- * example with `useMemo`, so that decorations are not rebuilt on every
- * render.
- */
- cursors: readonly TCursor[]
- renderCursor: (cursor: TCursor) => (props: PropsWithChildren) => ReactElement
-}
-
-/**
- * The local user's selection, deduped by value.
- *
- * The editor produces a fresh selection object on every snapshot change, so
- * subscribing to it directly would report presence far more often than the
- * caret actually moves.
- *
- * @public
- */
-export function useLocalSelection(): EditorSelection {
- const editor = useEditor()
- // Direction is ignored, which `isEqualSelections` already does: a caret is
- // drawn at the focus point, so reversing a selection moves nothing.
- return useEditorSelector(editor, getSelection, isEqualSelections)
-}
-
-/**
- * Turns remote cursors into range decorations, keeping each caret anchored as
- * the local user edits.
- *
- * Knows nothing about Sanity or the SDK, so it can also drive carets from
- * another source or from a test fixture. `useSDKPresenceCursors` is the version
- * wired to SDK presence.
- *
- * @public
- */
-export function useRemoteCursors(
- options: UseRemoteCursorsOptions,
-): RangeDecoration[] {
- const {cursors, renderCursor} = options
- // Only the moved carets need to survive a render. Where every caret is drawn
- // is derived from them plus the latest report, so there is no state to keep
- // in step with the incoming cursors.
- const [overrides, setOverrides] =
- useState>(EMPTY_OVERRIDES)
-
- const onCursorMoved = useCallback(
- (cursor: TCursor, selection: EditorSelection) => {
- setOverrides((previous) =>
- recordCursorMove(previous, cursors, cursor, selection),
- )
- },
- [cursors],
- )
-
- return useMemo(
- () => toRangeDecorations({cursors, overrides, renderCursor, onCursorMoved}),
- [cursors, overrides, renderCursor, onCursorMoved],
- )
-}
-
-const EMPTY_OVERRIDES: ReadonlyMap = new Map()
diff --git a/packages/plugin-sdk-value/src/plugin.sdk-comments.tsx b/packages/plugin-sdk-value/src/plugin.sdk-comments.tsx
deleted file mode 100644
index 18b406780c..0000000000
--- a/packages/plugin-sdk-value/src/plugin.sdk-comments.tsx
+++ /dev/null
@@ -1,297 +0,0 @@
-import {
- useEditor,
- useEditorSelector,
- type EditorSelection,
- type RangeDecoration,
-} from '@portabletext/editor'
-import {
- getSelectedTextBlocks,
- getSelection,
-} from '@portabletext/editor/selectors'
-import {
- isEqualSelectionPoints,
- isEqualSelections,
-} from '@portabletext/editor/utils'
-import {stringifyPath} from '@sanity/json-match'
-import {
- useCommentActions,
- useComments,
- type Comment,
- type CommentMessage,
- type DocumentHandle,
-} from '@sanity/sdk-react'
-import {
- useCallback,
- useMemo,
- useState,
- type PropsWithChildren,
- type ReactElement,
-} from 'react'
-import {
- relativeCommentPath,
- resolveCommentSelections,
- type AnchoredComment,
-} from './comments-anchoring'
-import {
- buildStoredSelection,
- type SelectedTextBlock,
-} from './comments-selection'
-import {arrayifyPath} from './plugin.sdk-value'
-
-const NO_MOVES: Record = {}
-
-/**
- * Anchors count as unchanged when every comment still sits at the same spot,
- * so resolving on each editor emission only re-renders when a highlight
- * actually needs to draw somewhere else.
- */
-function sameAnchors(a: AnchoredComment[], b: AnchoredComment[]): boolean {
- if (a.length !== b.length) {
- return false
- }
- return a.every((anchor, index) => {
- const other = b[index]
- return (
- anchor.commentId === other.commentId &&
- isEqualSelectionPoints(anchor.selection.anchor, other.selection.anchor) &&
- isEqualSelectionPoints(anchor.selection.focus, other.selection.focus)
- )
- })
-}
-
-/**
- * Draws one comment's highlight. The plugin has no opinion about how a
- * highlight looks, so it is the caller's to provide, the same way presence
- * takes `renderCursor`.
- *
- * @public
- */
-export type RenderCommentDecorationFunction = (
- comment: Comment,
-) => (props: PropsWithChildren) => ReactElement
-
-/**
- * Options for {@link useSDKCommentDecorations}.
- *
- * @public
- */
-export interface UseSDKCommentDecorationsOptions extends DocumentHandle {
- /**
- * The document path of the Portable Text field, for example `content`. The
- * same form `SDKValuePlugin` takes.
- */
- path: string
- renderDecoration: RenderCommentDecorationFunction
-}
-
-/**
- * Inline comment highlights for a Portable Text field, as range decorations.
- *
- * Pass the result to ``. Each
- * thread's first comment that carries a text anchor on this field gets one
- * decoration. Highlights stay put while the local user types, and a highlight
- * whose text has been deleted or rewritten beyond recognition is dropped
- * rather than drawn on the wrong words.
- *
- * Suspends while the document's comments load, like every SDK read hook.
- *
- * Resolved threads draw nothing: this mirrors the Studio, where resolving a
- * thread removes its highlight from the text.
- *
- * @public
- */
-export function useSDKCommentDecorations(
- options: UseSDKCommentDecorationsOptions,
-): RangeDecoration[] {
- const {path, renderDecoration, ...handle} = options
- const editor = useEditor()
- const {comments} = useComments({...handle})
-
- const inline = useMemo(() => {
- const basePath = arrayifyPath(path)
- return comments.flatMap((comment) => {
- if (
- comment.parentCommentId ||
- !comment.selection ||
- comment.status !== 'open'
- ) {
- return []
- }
- const relativePath = relativeCommentPath(basePath, comment.fieldPath)
- if (relativePath === undefined) {
- return []
- }
- return [{comment, relativePath, selection: comment.selection}]
- })
- }, [comments, path])
-
- // Resolved inside the selector so every resolution reads the text as it is
- // right now. Anything less fresh mis-anchors a comment written on text typed
- // since the staler reading, and on first load finds nothing at all, since
- // the field's value can arrive after the comments do. The anchor equality
- // keeps re-renders to actual highlight changes, and positions the editor is
- // already tracking through `onMoved` win over these resolutions anyway.
- const resolveAnchors = useCallback(
- (snapshot: {context: {value: unknown[]}}) =>
- resolveCommentSelections({
- value: snapshot.context.value,
- comments: inline.map(({comment, relativePath, selection}) => ({
- commentId: comment.id,
- relativePath,
- selection,
- })),
- }),
- [inline],
- )
- const anchored = useEditorSelector(editor, resolveAnchors, sameAnchors)
-
- // Moves are remembered against the comment list they were reported for, so a
- // re-resolution wins over stale positions without a state reset.
- const [moved, setMoved] = useState<{
- forComments: typeof inline
- selections: Record
- }>({forComments: inline, selections: {}})
- const movedSelections =
- moved.forComments === inline ? moved.selections : NO_MOVES
-
- return useMemo(() => {
- const commentsById = new Map(
- inline.map(({comment}) => [comment.id, comment]),
- )
-
- return anchored.flatMap((anchor) => {
- const comment = commentsById.get(anchor.commentId)
- if (!comment) {
- return []
- }
-
- const movedSelection = movedSelections[anchor.commentId]
- const selection =
- movedSelection === undefined ? anchor.selection : movedSelection
- if (selection === null) {
- // The editor reported the range lost, for example its text was deleted.
- return []
- }
-
- return [
- {
- component: renderDecoration(comment),
- selection,
- onMoved: ({newSelection}) => {
- setMoved((previous) => ({
- forComments: inline,
- selections: {
- ...(previous.forComments === inline ? previous.selections : {}),
- [anchor.commentId]: newSelection,
- },
- }))
- },
- payload: {commentId: anchor.commentId},
- } satisfies RangeDecoration,
- ]
- })
- }, [anchored, inline, movedSelections, renderDecoration])
-}
-
-/**
- * Options for {@link useSDKCommentAuthoring}.
- *
- * @public
- */
-export interface UseSDKCommentAuthoringOptions extends DocumentHandle {
- /**
- * The document path of the Portable Text field, for example `content`.
- */
- path: string
-}
-
-/**
- * What {@link useSDKCommentAuthoring} returns.
- *
- * @public
- */
-export interface SDKCommentAuthoring {
- /**
- * The current selection when it can take a comment, `null` otherwise. Show
- * the comment affordance when this is set, and position it off the
- * selection. A selection can take a comment when it is expanded, contains
- * text, and stays within one array of blocks.
- */
- commentableSelection: EditorSelection
- /**
- * Starts a comment thread anchored to the text selected right now.
- *
- * The anchor is captured from the live selection at call time, so call this
- * from the affordance while the selection still stands. Rejects when nothing
- * commentable is selected.
- */
- createInlineComment: (options: {
- message: CommentMessage
- /** Reuse the id of a failed comment to retry it. */
- commentId?: string
- }) => Promise
-}
-
-/** Reports the selection when it can take a comment, `null` otherwise. */
-function getCommentableSelection(
- snapshot: Parameters[0],
-): EditorSelection {
- const selection = getSelection(snapshot)
- const built = buildStoredSelection({
- selection,
- selectedBlocks: getSelectedTextBlocks(snapshot) as SelectedTextBlock[],
- })
- return built ? selection : null
-}
-
-/**
- * Lets the app author inline comments on a Portable Text field.
- *
- * The plugin captures the selection and writes the comment; the composer UI is
- * the app's, the same split the Studio and Canvas use. Comments are written in
- * the shape the Studio stores, so a thread started here shows up there.
- *
- * @public
- */
-export function useSDKCommentAuthoring(
- options: UseSDKCommentAuthoringOptions,
-): SDKCommentAuthoring {
- const {path, ...handle} = options
- const editor = useEditor()
- const {createComment} = useCommentActions()
-
- const commentableSelection = useEditorSelector(
- editor,
- getCommentableSelection,
- isEqualSelections,
- )
-
- return {
- commentableSelection,
- createInlineComment: ({message, commentId}) => {
- const snapshot = editor.getSnapshot()
- const built = buildStoredSelection({
- selection: getSelection(snapshot),
- selectedBlocks: getSelectedTextBlocks(snapshot) as SelectedTextBlock[],
- })
- if (!built) {
- return Promise.reject(
- new Error(
- 'Nothing commentable is selected, so there is nothing to anchor the comment to.',
- ),
- )
- }
-
- return createComment({
- ...handle,
- fieldPath: stringifyPath([
- ...arrayifyPath(path),
- ...built.containerPath,
- ]),
- selection: built.selection,
- message,
- ...(commentId === undefined ? {} : {commentId}),
- })
- },
- }
-}
diff --git a/packages/plugin-sdk-value/src/plugin.sdk-presence.tsx b/packages/plugin-sdk-value/src/plugin.sdk-presence.tsx
deleted file mode 100644
index 9c78858f11..0000000000
--- a/packages/plugin-sdk-value/src/plugin.sdk-presence.tsx
+++ /dev/null
@@ -1,163 +0,0 @@
-import type {EditorSelection, RangeDecoration} from '@portabletext/editor'
-import {
- usePresenceForDocument,
- useReportPresence,
- type DocumentHandle,
- type DocumentResource,
- type UseReportPresenceOptions,
-} from '@sanity/sdk-react'
-import {useMemo, type PropsWithChildren, type ReactElement} from 'react'
-import {useLocalSelection, useRemoteCursors} from './plugin.presence-sync'
-import {arrayifyPath} from './plugin.sdk-value'
-import {normalizeDocumentHandle} from './sdk-document-handle'
-
-/**
- * `@sanity/sdk-react` exports the presence hooks and their option types but not
- * the presence data types, so these are derived from what it does export.
- */
-type DocumentPresence = ReturnType<
- typeof usePresenceForDocument
->['presence'][number]
-
-/**
- * Draws one remote participant's caret. This package has no opinion about how a
- * caret looks, so it is the caller's to provide.
- *
- * @public
- */
-export type RenderCursorFunction = (
- cursor: SDKRemoteCursor,
-) => (props: PropsWithChildren) => ReactElement
-
-/**
- * A remote participant's caret, together with who they are.
- *
- * Declared in full rather than extending the internal cursor type, so nothing in
- * the public API refers to a type consumers cannot import.
- *
- * @public
- */
-export interface SDKRemoteCursor {
- /**
- * Identifies one editing session rather than one person. The same user in two
- * tabs reports two sessions and therefore draws two carets.
- */
- sessionId: string
- /**
- * Where the participant last reported their selection.
- */
- selection: EditorSelection
- user: DocumentPresence['user']
-}
-
-/**
- * Props for {@link SDKPresencePlugin}.
- *
- * @public
- */
-export interface SDKPresencePluginProps extends DocumentHandle {
- /**
- * @deprecated Use `resource` instead.
- */
- source?: DocumentResource
- /**
- * The document path of the Portable Text field, for example `content`. The
- * same form `SDKValuePlugin` takes.
- */
- path: string
-}
-
-/**
- * Options for {@link useSDKPresenceCursors}.
- *
- * @public
- */
-export interface UseSDKPresenceCursorsOptions extends DocumentHandle {
- /**
- * @deprecated Use `resource` instead.
- */
- source?: DocumentResource
- path: string
- renderCursor: RenderCursorFunction
-}
-
-/**
- * Reports the local user's caret in a Portable Text field, so other people in
- * the same document can see where they are.
- *
- * Place it inside `EditorProvider`. Prefer `SDKPortableTextEditable`, which
- * reports and draws in one component; reach for this when you render
- * `PortableTextEditable` yourself.
- *
- * Which document is reported follows the handle's perspective, or the ambient
- * one from `ResourceProvider`. Pass the plain document id and let the
- * perspective select the draft, the published document, or a release version.
- *
- * @public
- */
-export function SDKPresencePlugin(props: SDKPresencePluginProps) {
- const {path, ...handle} = normalizeDocumentHandle(props)
- const selection = useLocalSelection()
- const fieldPath = useFieldPath(path)
-
- useReportPresence({...handle, path: fieldPath, selection})
-
- return null
-}
-
-/**
- * Other people's carets in a Portable Text field, as range decorations.
- *
- * Pass the result to ``, or use
- * `SDKPortableTextEditable` and skip the wiring. Each caret stays anchored as
- * the local user types, and disappears when the participant leaves or their
- * session expires.
- *
- * The local user is never included, so an app does not draw its own caret.
- * Participants are counted by session, so the same person in two tabs draws two
- * carets.
- *
- * @public
- */
-export function useSDKPresenceCursors(
- options: UseSDKPresenceCursorsOptions,
-): RangeDecoration[] {
- const {path, renderCursor, ...handle} = normalizeDocumentHandle(options)
- const fieldPath = useFieldPath(path)
- // Exact id matching: a caret reported while editing a draft must not be drawn
- // in a release version of the same document, where the text differs.
- const {presence} = usePresenceForDocument({
- ...handle,
- path: fieldPath,
- excludeVersions: true,
- })
-
- const cursors = useMemo(
- () =>
- presence.flatMap((participant): SDKRemoteCursor[] =>
- participant.selection
- ? [
- {
- sessionId: participant.sessionId,
- selection: participant.selection,
- user: participant.user,
- },
- ]
- : [],
- ),
- [presence],
- )
-
- return useRemoteCursors({cursors, renderCursor})
-}
-
-/**
- * The SDK's presence hooks address fields by path array, because a field-level
- * path inside Portable Text needs keyed segments. This package takes the same
- * string expression as `SDKValuePlugin` everywhere and converts here.
- */
-function useFieldPath(
- path: string,
-): NonNullable {
- return useMemo(() => arrayifyPath(path), [path])
-}
diff --git a/packages/plugin-sdk-value/src/plugin.sdk-value.test.ts b/packages/plugin-sdk-value/src/plugin.sdk-value.test.ts
deleted file mode 100644
index 0015925eb0..0000000000
--- a/packages/plugin-sdk-value/src/plugin.sdk-value.test.ts
+++ /dev/null
@@ -1,633 +0,0 @@
-import type {PortableTextBlock} from '@portabletext/editor'
-import {describe, expect, test} from 'vitest'
-import {
- arrayifyPath,
- canApplyToValue,
- convertPatches,
- convertPatchesToSanity,
- findSidecarArrayPath,
- scopeRemotePatches,
- stringifyPatchPath,
- toEngineSafePatches,
- toMergeableMarkDefsPatches,
-} from './plugin.sdk-value'
-
-type PtePatchList = Parameters[0]
-
-describe(arrayifyPath.name, () => {
- test('property paths', () => {
- expect(arrayifyPath('foo')).toEqual(['foo'])
- expect(arrayifyPath('foo.bar')).toEqual(['foo', 'bar'])
- })
-
- test('array index paths', () => {
- expect(arrayifyPath('items[0]')).toEqual(['items', 0])
- expect(arrayifyPath('items[0].text')).toEqual(['items', 0, 'text'])
- })
-
- test('key-based paths', () => {
- expect(arrayifyPath('[_key=="abc"]')).toEqual([{_key: 'abc'}])
- expect(arrayifyPath('[_key=="abc"].children')).toEqual([
- {_key: 'abc'},
- 'children',
- ])
- expect(arrayifyPath('[_key=="abc"].children[_key=="def"]')).toEqual([
- {_key: 'abc'},
- 'children',
- {_key: 'def'},
- ])
- })
-
- test('throws on empty path', () => {
- expect(() => arrayifyPath('')).toThrow()
- })
-})
-
-describe(convertPatches.name, () => {
- test('set patches', () => {
- expect(
- convertPatches([
- {set: {'[_key=="k0"].children[_key=="k1"].text': 'Hello'}},
- ]),
- ).toEqual([
- {
- type: 'set',
- origin: 'remote',
- path: [{_key: 'k0'}, 'children', {_key: 'k1'}, 'text'],
- value: 'Hello',
- },
- ])
- })
-
- test('unset patches', () => {
- expect(convertPatches([{unset: ['[_key=="k0"]']}])).toEqual([
- {
- type: 'unset',
- origin: 'remote',
- path: [{_key: 'k0'}],
- },
- ])
- })
-
- test('insert patches', () => {
- expect(
- convertPatches([
- {
- insert: {
- after: '[_key=="k0"]',
- items: [{_type: 'block', _key: 'k1', children: []}],
- },
- },
- ]),
- ).toEqual([
- {
- type: 'insert',
- origin: 'remote',
- position: 'after',
- path: [{_key: 'k0'}],
- items: [{_type: 'block', _key: 'k1', children: []}],
- },
- ])
- })
-
- test('diffMatchPatch patches', () => {
- expect(
- convertPatches([
- {
- diffMatchPatch: {
- '[_key=="k0"].children[_key=="k1"].text':
- '@@ -1,3 +1,6 @@\n foo\n+bar\n',
- },
- },
- ]),
- ).toEqual([
- {
- type: 'diffMatchPatch',
- origin: 'remote',
- path: [{_key: 'k0'}, 'children', {_key: 'k1'}, 'text'],
- value: '@@ -1,3 +1,6 @@\n foo\n+bar\n',
- },
- ])
- })
-})
-
-describe(stringifyPatchPath.name, () => {
- test('property paths', () => {
- expect(stringifyPatchPath(['foo'])).toEqual('foo')
- expect(stringifyPatchPath(['foo', 'bar'])).toEqual('foo.bar')
- })
-
- test('array index paths', () => {
- expect(stringifyPatchPath(['items', 0])).toEqual('items[0]')
- expect(stringifyPatchPath(['items', 0, 'text'])).toEqual('items[0].text')
- })
-
- test('key-based paths', () => {
- expect(
- stringifyPatchPath([{_key: 'abc'}, 'children', {_key: 'def'}, 'text']),
- ).toEqual('[_key=="abc"].children[_key=="def"].text')
- })
-
- test('empty path', () => {
- expect(stringifyPatchPath([])).toEqual('')
- })
-
- test('round-trips through arrayifyPath', () => {
- const path = [{_key: 'abc'}, 'children', {_key: 'def'}, 'marks', 0]
- expect(arrayifyPath(stringifyPatchPath(path))).toEqual(path)
- })
-})
-
-describe(convertPatchesToSanity.name, () => {
- test('set patches', () => {
- expect(
- convertPatchesToSanity(
- [
- {
- type: 'set',
- path: [{_key: 'k0'}, 'children', {_key: 'k1'}, 'text'],
- value: 'Hello',
- },
- ],
- {prefix: 'blocks'},
- ),
- ).toEqual([
- {set: {'blocks[_key=="k0"].children[_key=="k1"].text': 'Hello'}},
- ])
- })
-
- test('unset patches', () => {
- expect(
- convertPatchesToSanity([{type: 'unset', path: [{_key: 'k0'}]}], {
- prefix: 'blocks',
- }),
- ).toEqual([{unset: ['blocks[_key=="k0"]']}])
- })
-
- test('insert patches', () => {
- expect(
- convertPatchesToSanity(
- [
- {
- type: 'insert',
- position: 'after',
- path: [{_key: 'k0'}],
- items: [{_type: 'block', _key: 'k1', children: []}],
- },
- ],
- {prefix: 'blocks'},
- ),
- ).toEqual([
- {
- insert: {
- after: 'blocks[_key=="k0"]',
- items: [{_type: 'block', _key: 'k1', children: []}],
- },
- },
- ])
- })
-
- test('diffMatchPatch patches', () => {
- expect(
- convertPatchesToSanity(
- [
- {
- type: 'diffMatchPatch',
- path: [{_key: 'k0'}, 'children', {_key: 'k1'}, 'text'],
- value: '@@ -1,3 +1,6 @@\n foo\n+bar\n',
- },
- ],
- {prefix: 'blocks'},
- ),
- ).toEqual([
- {
- diffMatchPatch: {
- 'blocks[_key=="k0"].children[_key=="k1"].text':
- '@@ -1,3 +1,6 @@\n foo\n+bar\n',
- },
- },
- ])
- })
-
- test('empty path targets the field itself', () => {
- expect(
- convertPatchesToSanity([{type: 'set', path: [], value: []}], {
- prefix: 'blocks',
- }),
- ).toEqual([{set: {blocks: []}}])
- })
-
- test('root unset (emptied editor) writes an empty array instead', () => {
- expect(
- convertPatchesToSanity([{type: 'unset', path: []}], {prefix: 'blocks'}),
- ).toEqual([{set: {blocks: []}}])
- })
-
- test('nested field prefix', () => {
- expect(
- convertPatchesToSanity([{type: 'unset', path: [{_key: 'k0'}]}], {
- prefix: 'content.body',
- }),
- ).toEqual([{unset: ['content.body[_key=="k0"]']}])
- })
-})
-
-describe(scopeRemotePatches.name, () => {
- test('re-roots patches under the field path', () => {
- expect(
- scopeRemotePatches(
- [
- {set: {'blocks[_key=="k0"].children[_key=="k1"].text': 'Hello'}},
- {unset: ['blocks[_key=="k0"].markDefs[_key=="m0"]']},
- ],
- 'blocks',
- ),
- ).toEqual([
- {
- type: 'set',
- origin: 'remote',
- path: [{_key: 'k0'}, 'children', {_key: 'k1'}, 'text'],
- value: 'Hello',
- },
- {
- type: 'unset',
- origin: 'remote',
- path: [{_key: 'k0'}, 'markDefs', {_key: 'm0'}],
- },
- ])
- })
-
- test('drops patches outside the field', () => {
- expect(
- scopeRemotePatches(
- [{set: {'title': 'New title', 'blocks[_key=="k0"].style': 'h1'}}],
- 'blocks',
- ),
- ).toEqual([
- {
- type: 'set',
- origin: 'remote',
- path: [{_key: 'k0'}, 'style'],
- value: 'h1',
- },
- ])
- })
-
- test('returns null when the whole field is replaced', () => {
- expect(scopeRemotePatches([{set: {blocks: []}}], 'blocks')).toBeNull()
- expect(scopeRemotePatches([{unset: ['blocks']}], 'blocks')).toBeNull()
- })
-
- test('returns null when an ancestor of the field is replaced', () => {
- expect(
- scopeRemotePatches([{set: {content: {}}}], 'content.body'),
- ).toBeNull()
- })
-
- test('handles insert patches anchored inside the field', () => {
- expect(
- scopeRemotePatches(
- [
- {
- insert: {
- after: 'blocks[_key=="k0"]',
- items: [{_type: 'block', _key: 'k1', children: []}],
- },
- },
- ],
- 'blocks',
- ),
- ).toEqual([
- {
- type: 'insert',
- origin: 'remote',
- position: 'after',
- path: [{_key: 'k0'}],
- items: [{_type: 'block', _key: 'k1', children: []}],
- },
- ])
- })
-})
-
-describe(toMergeableMarkDefsPatches.name, () => {
- const storeValue = [
- {
- _type: 'block',
- _key: 'b1',
- children: [
- {_type: 'span', _key: 's1', text: 'Hello', marks: ['m1']},
- {_type: 'span', _key: 's2', text: ' world', marks: []},
- ],
- markDefs: [
- {_type: 'link', _key: 'm1', href: 'https://example.com'},
- {_type: 'link', _key: 'm2', href: 'https://unreferenced.example'},
- ],
- style: 'normal',
- },
- ] as unknown as PortableTextBlock[]
-
- test('new definitions become inserts', () => {
- expect(
- toMergeableMarkDefsPatches(
- [
- {
- type: 'set',
- path: [{_key: 'b1'}, 'markDefs'],
- value: [
- {_type: 'link', _key: 'm1', href: 'https://example.com'},
- {_type: 'link', _key: 'm2', href: 'https://unreferenced.example'},
- {_type: 'link', _key: 'new', href: 'https://new.example'},
- ],
- },
- ],
- () => storeValue,
- ),
- ).toEqual([
- // The keyed unset makes the insert an upsert: a re-send self-cleans
- // an earlier copy the store view failed to show, instead of stacking
- // a duplicate.
- {
- type: 'unset',
- origin: undefined,
- path: [{_key: 'b1'}, 'markDefs', {_key: 'new'}],
- },
- {
- type: 'insert',
- origin: undefined,
- position: 'after',
- path: [{_key: 'b1'}, 'markDefs', -1],
- items: [{_type: 'link', _key: 'new', href: 'https://new.example'}],
- },
- ])
- })
-
- test('changed definitions become keyed sets', () => {
- expect(
- toMergeableMarkDefsPatches(
- [
- {
- type: 'set',
- path: [{_key: 'b1'}, 'markDefs'],
- value: [
- {_type: 'link', _key: 'm1', href: 'https://updated.example'},
- {_type: 'link', _key: 'm2', href: 'https://unreferenced.example'},
- ],
- },
- ],
- () => storeValue,
- ),
- ).toEqual([
- {
- type: 'set',
- origin: undefined,
- path: [{_key: 'b1'}, 'markDefs', {_key: 'm1'}],
- value: {_type: 'link', _key: 'm1', href: 'https://updated.example'},
- },
- ])
- })
-
- test('unreferenced removals become keyed unsets', () => {
- expect(
- toMergeableMarkDefsPatches(
- [
- {
- type: 'set',
- path: [{_key: 'b1'}, 'markDefs'],
- value: [{_type: 'link', _key: 'm1', href: 'https://example.com'}],
- },
- ],
- () => storeValue,
- ),
- ).toEqual([
- {
- type: 'unset',
- origin: undefined,
- path: [{_key: 'b1'}, 'markDefs', {_key: 'm2'}],
- },
- ])
- })
-
- test('never removes definitions the store spans still reference', () => {
- // a diverged client prunes m1 spuriously (it cannot see the spans that
- // reference it); m2 is unreferenced so its removal goes through
- expect(
- toMergeableMarkDefsPatches(
- [{type: 'set', path: [{_key: 'b1'}, 'markDefs'], value: []}],
- () => storeValue,
- ),
- ).toEqual([
- {
- type: 'unset',
- origin: undefined,
- path: [{_key: 'b1'}, 'markDefs', {_key: 'm2'}],
- },
- ])
- })
-
- test('identical arrays produce no operations', () => {
- expect(
- toMergeableMarkDefsPatches(
- [
- {
- type: 'set',
- path: [{_key: 'b1'}, 'markDefs'],
- value: [
- {_type: 'link', _key: 'm1', href: 'https://example.com'},
- {_type: 'link', _key: 'm2', href: 'https://unreferenced.example'},
- ],
- },
- ],
- () => storeValue,
- ),
- ).toEqual([])
- })
-
- test('leaves non-markDefs patches untouched', () => {
- const patches = [
- {
- type: 'set',
- path: [{_key: 'b1'}, 'children', {_key: 's1'}, 'marks'],
- value: ['strong'],
- },
- ] as PtePatchList
- expect(toMergeableMarkDefsPatches(patches, () => storeValue)).toEqual(
- patches,
- )
- })
-})
-
-describe(canApplyToValue.name, () => {
- const value = [
- {
- _type: 'block',
- _key: 'b1',
- children: [{_type: 'span', _key: 's1', text: 'Hello', marks: []}],
- markDefs: [],
- style: 'normal',
- },
- ] as unknown as PortableTextBlock[]
-
- test('resolvable operations pass', () => {
- expect(canApplyToValue({type: 'unset', path: [{_key: 'b1'}]}, value)).toBe(
- true,
- )
- expect(
- canApplyToValue(
- {
- type: 'diffMatchPatch',
- path: [{_key: 'b1'}, 'children', {_key: 's1'}, 'text'],
- value: '@@',
- },
- value,
- ),
- ).toBe(true)
- expect(
- canApplyToValue(
- {type: 'insert', position: 'after', path: [{_key: 'b1'}], items: []},
- value,
- ),
- ).toBe(true)
- })
-
- test('operations addressing missing nodes are rejected', () => {
- expect(
- canApplyToValue(
- {type: 'unset', path: [{_key: 'b1'}, 'children', {_key: 'gone'}]},
- value,
- ),
- ).toBe(false)
- expect(
- canApplyToValue(
- {type: 'insert', position: 'after', path: [{_key: 'gone'}], items: []},
- value,
- ),
- ).toBe(false)
- })
-
- test('set only requires the parent to resolve', () => {
- expect(
- canApplyToValue(
- {
- type: 'set',
- path: [{_key: 'b1'}, 'children', {_key: 's1'}, 'newProp'],
- value: 1,
- },
- value,
- ),
- ).toBe(true)
- expect(
- canApplyToValue(
- {
- type: 'set',
- path: [{_key: 'b1'}, 'children', {_key: 'gone'}, 'text'],
- value: '',
- },
- value,
- ),
- ).toBe(false)
- })
-
- test('passes everything through when the value is unknown', () => {
- expect(
- canApplyToValue({type: 'unset', path: [{_key: 'gone'}]}, undefined),
- ).toBe(true)
- })
-})
-
-describe(findSidecarArrayPath.name, () => {
- test('passes through paths the engine can resolve', () => {
- expect(findSidecarArrayPath([{_key: 'b1'}])).toBeNull()
- expect(findSidecarArrayPath([{_key: 'b1'}, 'style'])).toBeNull()
- expect(
- findSidecarArrayPath([{_key: 'b1'}, 'children', {_key: 's1'}, 'text']),
- ).toBeNull()
- expect(findSidecarArrayPath([{_key: 'b1'}, 'markDefs'])).toBeNull()
- expect(
- findSidecarArrayPath([{_key: 'b1'}, 'children', {_key: 's1'}, 'marks']),
- ).toBeNull()
- })
-
- test('detects items addressed inside sidecar arrays', () => {
- expect(
- findSidecarArrayPath([{_key: 'b1'}, 'markDefs', {_key: 'm1'}]),
- ).toEqual([{_key: 'b1'}, 'markDefs'])
- expect(
- findSidecarArrayPath([{_key: 'b1'}, 'markDefs', {_key: 'm1'}, 'href']),
- ).toEqual([{_key: 'b1'}, 'markDefs'])
- expect(
- findSidecarArrayPath([
- {_key: 'b1'},
- 'children',
- {_key: 's1'},
- 'marks',
- 2,
- ]),
- ).toEqual([{_key: 'b1'}, 'children', {_key: 's1'}, 'marks'])
- })
-})
-
-describe(toEngineSafePatches.name, () => {
- const targetValue = [
- {
- _type: 'block',
- _key: 'b1',
- children: [{_type: 'span', _key: 's1', text: 'Hello', marks: ['m1']}],
- markDefs: [{_type: 'link', _key: 'm1', href: 'https://example.com'}],
- style: 'normal',
- },
- ] as unknown as PortableTextBlock[]
-
- test('passes resolvable patches through unchanged', () => {
- const patches = convertPatches([
- {set: {'[_key=="b1"].children[_key=="s1"].text': 'Hello'}},
- ])
- expect(toEngineSafePatches(patches, targetValue)).toEqual(patches)
- })
-
- test('coalesces sidecar item patches into whole-property sets', () => {
- const patches = convertPatches([
- {
- unset: ['[_key=="b1"].markDefs[_key=="m0"]'],
- insert: {
- after: '[_key=="b1"].markDefs[_key=="m0"]',
- items: [{_type: 'link', _key: 'm1', href: 'https://example.com'}],
- },
- },
- ])
- expect(toEngineSafePatches(patches, targetValue)).toEqual([
- {
- type: 'set',
- origin: 'remote',
- path: [{_key: 'b1'}, 'markDefs'],
- value: [{_type: 'link', _key: 'm1', href: 'https://example.com'}],
- },
- ])
- })
-
- test('unsets the property when absent from the target value', () => {
- const patches = convertPatches([
- {unset: ['[_key=="b2"].markDefs[_key=="m0"]']},
- ])
- expect(toEngineSafePatches(patches, targetValue)).toEqual([
- {
- type: 'unset',
- origin: 'remote',
- path: [{_key: 'b2'}, 'markDefs'],
- },
- ])
- })
-
- test('coalesces indexed marks patches into a whole-array set', () => {
- const patches = convertPatches([
- {unset: ['[_key=="b1"].children[_key=="s1"].marks[2]']},
- ])
- expect(toEngineSafePatches(patches, targetValue)).toEqual([
- {
- type: 'set',
- origin: 'remote',
- path: [{_key: 'b1'}, 'children', {_key: 's1'}, 'marks'],
- value: ['m1'],
- },
- ])
- })
-})
diff --git a/packages/plugin-sdk-value/src/plugin.sdk-value.tsx b/packages/plugin-sdk-value/src/plugin.sdk-value.tsx
deleted file mode 100644
index 2ea96604e2..0000000000
--- a/packages/plugin-sdk-value/src/plugin.sdk-value.tsx
+++ /dev/null
@@ -1,1296 +0,0 @@
-import {
- useEditor,
- type Editor,
- type PortableTextBlock,
- type Patch as PtePatch,
-} from '@portabletext/editor'
-import {
- applyAll,
- type JSONValue,
- type Path,
- type PathSegment,
- type InsertPatch as PteInsertPatch,
-} from '@portabletext/patches'
-import {diffValue, type SanityPatchOperations} from '@sanity/diff-patch'
-import {
- parsePath,
- type ExprNode,
- type PathNode,
- type SegmentNode,
- type ThisNode,
-} from '@sanity/json-match'
-import {
- editDocument,
- getDocumentState,
- subscribeDocumentEvents,
- useApplyDocumentActions,
- useEditDocument,
- useSanityInstance,
- type DocumentHandle,
- type DocumentResource,
- type EditDocumentAction,
-} from '@sanity/sdk-react'
-import {useActorRef} from '@xstate/react'
-import {useCallback} from 'react'
-import {fromCallback, setup, type AnyEventObject} from 'xstate'
-import {debug} from './debug'
-import {normalizeDocumentHandle} from './sdk-document-handle'
-
-type InsertPatch = Required>
-
-const ARRAYIFY_ERROR_MESSAGE =
- 'Unexpected path format from diffValue output. Please report this issue.'
-
-function* getSegments(
- node: PathNode,
-): Generator> {
- if (node.base) {
- yield* getSegments(node.base)
- }
- if (node.segment.type !== 'This') {
- yield node.segment
- }
-}
-
-function isKeyPath(node: ExprNode): node is PathNode {
- if (node.type !== 'Path') {
- return false
- }
- if (node.base) {
- return false
- }
- if (node.recursive) {
- return false
- }
- if (node.segment.type !== 'Identifier') {
- return false
- }
- return node.segment.name === '_key'
-}
-
-export function arrayifyPath(pathExpr: string): Path {
- const node = parsePath(pathExpr)
- if (!node) {
- return []
- }
- if (node.type !== 'Path') {
- throw new Error(ARRAYIFY_ERROR_MESSAGE)
- }
-
- return Array.from(getSegments(node)).map((segment): PathSegment => {
- if (segment.type === 'Identifier') {
- return segment.name
- }
- if (segment.type !== 'Subscript') {
- throw new Error(ARRAYIFY_ERROR_MESSAGE)
- }
- if (segment.elements.length !== 1) {
- throw new Error(ARRAYIFY_ERROR_MESSAGE)
- }
-
- const [element] = segment.elements
- if (element.type === 'Number') {
- return element.value
- }
-
- if (element.type !== 'Comparison') {
- throw new Error(ARRAYIFY_ERROR_MESSAGE)
- }
- if (element.operator !== '==') {
- throw new Error(ARRAYIFY_ERROR_MESSAGE)
- }
- const keyPathNode = [element.left, element.right].find(isKeyPath)
- if (!keyPathNode) {
- throw new Error(ARRAYIFY_ERROR_MESSAGE)
- }
- const other = element.left === keyPathNode ? element.right : element.left
- if (other.type !== 'String') {
- throw new Error(ARRAYIFY_ERROR_MESSAGE)
- }
- return {_key: other.value}
- })
-}
-
-export function convertPatches(patches: SanityPatchOperations[]): PtePatch[] {
- return patches.flatMap((p) => {
- return Object.entries(p).flatMap(([type, values]): PtePatch[] => {
- const origin = 'remote'
-
- switch (type) {
- case 'set':
- case 'setIfMissing':
- case 'diffMatchPatch':
- case 'inc':
- case 'dec': {
- return Object.entries(values).map(
- ([pathExpr, value]) =>
- ({type, value, origin, path: arrayifyPath(pathExpr)}) as PtePatch,
- )
- }
- case 'unset': {
- if (!Array.isArray(values)) {
- return []
- }
- return values.map(arrayifyPath).map((path) => ({type, origin, path}))
- }
- case 'insert': {
- const {items, ...rest} = values as InsertPatch['insert']
- type InsertPosition = PteInsertPatch['position']
- const position = Object.keys(rest).at(0) as InsertPosition | undefined
-
- if (!position) {
- return []
- }
- const pathExpr = (rest as {[K in InsertPosition]: string})[position]
- const insertPatch: PteInsertPatch = {
- type,
- origin,
- position,
- path: arrayifyPath(pathExpr),
- items: items as JSONValue[],
- }
-
- return [insertPatch]
- }
-
- default: {
- return []
- }
- }
- })
- })
-}
-
-const STRINGIFY_ERROR_MESSAGE =
- 'Unable to convert an editor patch path to a Sanity path expression.'
-
-/**
- * Converts a Portable Text Editor patch path (an array of segments) into a
- * Sanity json-match path expression. The inverse of `arrayifyPath`.
- *
- * @internal
- */
-export function stringifyPatchPath(path: Path): string {
- let result = ''
- for (const segment of path) {
- if (typeof segment === 'string') {
- result = result === '' ? segment : `${result}.${segment}`
- } else if (typeof segment === 'number') {
- result = `${result}[${segment}]`
- } else if (
- typeof segment === 'object' &&
- segment !== null &&
- '_key' in segment
- ) {
- result = `${result}[_key=="${segment._key}"]`
- } else {
- throw new Error(STRINGIFY_ERROR_MESSAGE)
- }
- }
- return result
-}
-
-function prefixPathExpression(prefix: string, expression: string): string {
- if (expression === '') {
- return prefix
- }
- return expression.startsWith('[')
- ? `${prefix}${expression}`
- : `${prefix}.${expression}`
-}
-
-/**
- * `SanityPatchOperations` from `@sanity/diff-patch` only covers the
- * operations `diffValue` emits; the editor can additionally produce these.
- */
-type SanityPatchOperationsWithExtras = SanityPatchOperations & {
- setIfMissing?: {[path: string]: unknown}
- inc?: {[path: string]: number}
- dec?: {[path: string]: number}
-}
-
-/**
- * Converts Portable Text Editor patches into Sanity patch operations rooted
- * at the given document field path. Throws if a patch cannot be converted;
- * callers should fall back to pushing the whole value.
- *
- * @internal
- */
-export function convertPatchesToSanity(
- patches: PtePatch[],
- options: {prefix: string},
-): SanityPatchOperationsWithExtras[] {
- return patches.map((patch): SanityPatchOperationsWithExtras => {
- const pathExpression = prefixPathExpression(
- options.prefix,
- stringifyPatchPath(patch.path),
- )
-
- switch (patch.type) {
- case 'set':
- return {set: {[pathExpression]: patch.value}}
- case 'setIfMissing':
- return {setIfMissing: {[pathExpression]: patch.value}}
- case 'unset':
- // The editor unsets the whole field when it becomes empty. Write an
- // empty array instead: unsetting the field would leave other clients
- // unable to reconcile against it (their remote value disappears).
- if (patch.path.length === 0) {
- return {set: {[pathExpression]: []}}
- }
- return {unset: [pathExpression]}
- case 'diffMatchPatch':
- return {diffMatchPatch: {[pathExpression]: patch.value}}
- case 'inc':
- return {inc: {[pathExpression]: patch.value as number}}
- case 'dec':
- return {dec: {[pathExpression]: patch.value as number}}
- case 'insert':
- return {
- insert: {
- [patch.position]: pathExpression,
- items: patch.items,
- } as SanityPatchOperations['insert'],
- }
- default:
- throw new Error(STRINGIFY_ERROR_MESSAGE)
- }
- })
-}
-
-function segmentsEqual(a: PathSegment, b: PathSegment): boolean {
- if (typeof a === 'string' || typeof a === 'number') {
- return a === b
- }
- if (typeof b === 'string' || typeof b === 'number') {
- return false
- }
- if (Array.isArray(a) || Array.isArray(b)) {
- return false
- }
- return a._key === b._key
-}
-
-function pathsEqual(a: Path, b: Path): boolean {
- return (
- a.length === b.length &&
- a.every((segment, index) => segmentsEqual(segment, b[index]))
- )
-}
-
-/**
- * The editor engine can only resolve keyed/indexed segments against the
- * root block array and (possibly nested) `children` arrays. Operations
- * that address items of any other array, e.g. a block's `markDefs` or a
- * span's `marks`, misapply. When a patch path enters such a sidecar
- * array, this returns the path of the array itself so callers can fall
- * back to replacing the whole property; returns `null` for paths the
- * engine can apply.
- *
- * @internal
- */
-export function findSidecarArrayPath(path: Path): Path | null {
- // a keyed/numeric segment is only resolvable first (root block array)
- // or directly after a `children` property
- let expectNode = true
- for (let index = 0; index < path.length; index++) {
- const segment = path[index]
- if (typeof segment === 'string') {
- expectNode = segment === 'children'
- } else {
- if (!expectNode) {
- return path.slice(0, index)
- }
- expectNode = false
- }
- }
- return null
-}
-
-function getValueAtPath(value: JSONValue, path: Path): JSONValue | undefined {
- let current: JSONValue | undefined = value
- for (const segment of path) {
- if (current === null || current === undefined) {
- return undefined
- }
- if (typeof segment === 'number') {
- if (!Array.isArray(current)) {
- return undefined
- }
- current = current[segment < 0 ? current.length + segment : segment]
- } else if (typeof segment === 'string') {
- if (typeof current !== 'object' || Array.isArray(current)) {
- return undefined
- }
- current = (current as {[key: string]: JSONValue})[segment]
- } else if (Array.isArray(segment)) {
- // index tuples address ranges, not single values
- return undefined
- } else {
- if (!Array.isArray(current)) {
- return undefined
- }
- current = current.find(
- (item) =>
- typeof item === 'object' &&
- item !== null &&
- !Array.isArray(item) &&
- (item as {_key?: unknown})._key === segment._key,
- )
- }
- }
- return current
-}
-
-/**
- * Converts a target-value diff into patches the editor engine can apply.
- * Patches addressing items inside sidecar arrays are coalesced into whole
- * `set`s (or `unset`s) of the owning property, taken from the target
- * value.
- *
- * @internal
- */
-export function toEngineSafePatches(
- patches: PtePatch[],
- targetValue: PortableTextBlock[],
-): PtePatch[] {
- const safe: PtePatch[] = []
- const sidecarPaths: Path[] = []
-
- for (const patch of patches) {
- const sidecarPath = findSidecarArrayPath(patch.path)
- if (!sidecarPath) {
- safe.push(patch)
- continue
- }
- if (!sidecarPaths.some((existing) => pathsEqual(existing, sidecarPath))) {
- sidecarPaths.push(sidecarPath)
- }
- }
-
- for (const sidecarPath of sidecarPaths) {
- const value = getValueAtPath(
- targetValue as unknown as JSONValue,
- sidecarPath,
- )
- safe.push(
- value === undefined
- ? {type: 'unset', path: sidecarPath, origin: 'remote'}
- : {type: 'set', path: sidecarPath, value, origin: 'remote'},
- )
- }
-
- return safe
-}
-
-/**
- * Drops insert items whose `_key` is absent from the remote value. A text
- * paste can stage a temporary span and remove it again within the same
- * transaction; applying the insert without the cleanup would flash the
- * staged content. Callers must only run this once the store value reflects
- * the transaction the patches belong to (see `'apply remote patches'`),
- * otherwise every legitimately new node would be dropped.
- */
-function filterInsertsMissingFromRemoteValue(
- patches: PtePatch[],
- remoteValue: PortableTextBlock[],
-): PtePatch[] {
- return patches.flatMap((patch): PtePatch[] => {
- if (patch.type !== 'insert') {
- return [patch]
- }
-
- const parentValue = getValueAtPath(
- remoteValue as unknown as JSONValue,
- patch.path.slice(0, -1),
- )
- if (!Array.isArray(parentValue)) {
- return [patch]
- }
-
- const items = patch.items.filter((item) => {
- const itemKey = getKey(item)
- if (!itemKey) {
- return true
- }
- return parentValue.some((candidate) => getKey(candidate) === itemKey)
- })
-
- return items.length > 0 ? [{...patch, items}] : []
- })
-}
-
-function getKey(value: JSONValue): string | undefined {
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
- return undefined
- }
- const key = (value as {_key?: unknown})._key
- return typeof key === 'string' ? key : undefined
-}
-
-/**
- * The editor writes `markDefs` as whole-array `set`s. Two clients
- * formatting the same block concurrently then overwrite each other's
- * arrays at the server (last writer wins) while both clients' span
- * `marks` references survive, stranding marks without definitions.
- * Outgoing `markDefs` sets are therefore decomposed into item-level
- * operations against the store (server truth): new definitions insert,
- * changed definitions set by key, and removed definitions unset by key,
- * except definitions the store's own spans still reference (a diverged
- * client's normalizer prunes those spuriously; a later, converged flush
- * removes them for real). Item-keyed operations merge at the server
- * instead of overwriting.
- *
- * @internal
- */
-export function toMergeableMarkDefsPatches(
- patches: PtePatch[],
- getCurrentValue: () => PortableTextBlock[] | null | undefined,
-): PtePatch[] {
- return patches.flatMap((patch): PtePatch[] => {
- if (
- patch.type !== 'set' ||
- patch.path.at(-1) !== 'markDefs' ||
- !Array.isArray(patch.value)
- ) {
- return [patch]
- }
- const currentValue = getCurrentValue()
- if (!currentValue) {
- return [patch]
- }
- const root = currentValue as unknown as JSONValue
- const storeMarkDefs = getValueAtPath(root, patch.path)
- const storeBlock = getValueAtPath(root, patch.path.slice(0, -1))
- if (
- !Array.isArray(storeMarkDefs) ||
- typeof storeBlock !== 'object' ||
- storeBlock === null
- ) {
- return [patch]
- }
-
- const local = patch.value as Array<{_key?: string}>
- const store = storeMarkDefs as Array<{_key?: string}>
- if (local.some((item) => item._key === undefined)) {
- return [patch]
- }
-
- const referencedKeys = new Set(
- (
- (storeBlock as {children?: Array<{marks?: string[]}>}).children ?? []
- ).flatMap((child) => child.marks ?? []),
- )
- const storeByKey = new Map(store.map((item) => [item._key, item]))
- const localKeys = new Set(local.map((item) => item._key))
- const origin = patch.origin
-
- const ops: PtePatch[] = []
-
- const inserted = local.filter((item) => !storeByKey.has(item._key))
- if (inserted.length > 0) {
- for (const item of inserted) {
- if (item._key === undefined) {
- continue
- }
- // The store view can wrongly lack an in-flight insert (a colliding
- // transaction makes the optimistic rebase fail silently), so a
- // re-send would stack a duplicate. The keyed unset makes the
- // insert an upsert: it is a no-op while the key is absent, and
- // the client's own transactions apply in order, so a re-send
- // self-cleans any earlier copy instead of duplicating it.
- ops.push({
- type: 'unset',
- origin,
- path: [...patch.path, {_key: item._key}],
- })
- }
- ops.push({
- type: 'insert',
- origin,
- position: 'after',
- path: [...patch.path, -1],
- items: inserted as JSONValue[],
- })
- }
-
- for (const item of local) {
- const existing = storeByKey.get(item._key)
- if (existing && JSON.stringify(existing) !== JSON.stringify(item)) {
- ops.push({
- type: 'set',
- origin,
- path: [...patch.path, {_key: item._key as string}],
- value: item as JSONValue,
- })
- }
- }
-
- for (const item of store) {
- if (
- item._key !== undefined &&
- !localKeys.has(item._key) &&
- !referencedKeys.has(item._key)
- ) {
- ops.push({
- type: 'unset',
- origin,
- path: [...patch.path, {_key: item._key}],
- })
- }
- }
-
- return ops
- })
-}
-
-/**
- * Whether a remote patch can resolve against the given editor value.
- * Concurrent edits routinely produce operations addressing nodes another
- * client has already removed or not yet created; sending those into the
- * engine fails loudly (console errors) before being skipped. Callers drop
- * unresolvable patches up front and rely on the follow-up repair sync to
- * converge instead.
- *
- * @internal
- */
-export function canApplyToValue(
- patch: PtePatch,
- value: PortableTextBlock[] | undefined,
-): boolean {
- if (!value) {
- return true
- }
- const root = value as unknown as JSONValue
- switch (patch.type) {
- // unset needs the node itself; insert needs the sibling at `path`;
- // diffMatchPatch needs the existing string
- case 'unset':
- case 'insert':
- case 'diffMatchPatch':
- return getValueAtPath(root, patch.path) !== undefined
- // set creates its target property, so only the parent must resolve
- case 'set':
- return (
- patch.path.length === 0 ||
- getValueAtPath(root, patch.path.slice(0, -1)) !== undefined
- )
- default:
- return true
- }
-}
-
-/**
- * Filters a patch batch down to the patches that can resolve (see
- * `canApplyToValue`), checking each patch against the value as it stands
- * after the preceding patches applied. A transaction routinely inserts a
- * node and then addresses it, e.g. a span split followed by a `marks` set
- * on the new span, so checking every patch against the starting value
- * would drop valid operations.
- */
-function filterResolvablePatches(
- patches: PtePatch[],
- value: PortableTextBlock[] | undefined,
-): PtePatch[] {
- let projected = value
- const resolvable: PtePatch[] = []
- for (const patch of patches) {
- if (!canApplyToValue(patch, projected)) {
- continue
- }
- resolvable.push(patch)
- if (projected) {
- try {
- projected = applyAll(projected, [patch])
- } catch {
- // the engine applies best-effort too; keep the projection as-is
- }
- }
- }
- return resolvable
-}
-
-/**
- * Scopes document-rooted Sanity patches to the given field path, returning
- * field-relative Portable Text Editor patches. Patches outside the field are
- * dropped. Returns `null` when the field (or an ancestor of it) is replaced
- * wholesale, in which case the caller should fall back to a full value sync.
- * Throws when a path expression cannot be converted.
- *
- * @internal
- */
-export function scopeRemotePatches(
- patches: SanityPatchOperations[],
- fieldPath: string,
-): PtePatch[] | null {
- const prefix = arrayifyPath(fieldPath)
- const converted = convertPatches(patches)
- const scoped: PtePatch[] = []
-
- for (const patch of converted) {
- const overlap = Math.min(patch.path.length, prefix.length)
- let touchesField = true
- for (let index = 0; index < overlap; index++) {
- if (!segmentsEqual(patch.path[index], prefix[index])) {
- touchesField = false
- break
- }
- }
- if (!touchesField) {
- continue
- }
- if (patch.path.length <= prefix.length) {
- // the patch targets the field itself or an ancestor of it, which
- // cannot be expressed as a field-relative operation
- return null
- }
- scoped.push({...patch, path: patch.path.slice(prefix.length)})
- }
-
- return scoped
-}
-
-function debugTextOf(value: unknown): string {
- if (!Array.isArray(value)) {
- return ''
- }
- return value
- .map((block) =>
- Array.isArray((block as {children?: unknown}).children)
- ? ((block as {children: Array<{text?: string}>}).children ?? [])
- .map((child) => child.text ?? '')
- .join('')
- : '',
- )
- .join('\n')
-}
-
-/**
- * How long an editor-versus-store divergence must persist, unchanged,
- * before the whole-value repair acts on it. When a remote transaction
- * arrives interleaved with the listener echoes of this client's own recent
- * edits, the store value is transiently wrong until the echo returns and
- * the rebase corrects it. A repair fired inside that window copies the
- * garbage into the editor and a follow-up repair restores the text at a
- * drifted offset, scrambling words the user typed in the meantime. The
- * window therefore has to outlast a slow listener echo round trip; real
- * divergence is stable and loses nothing by being repaired a beat later.
- *
- * Tests use a short window: their mock stores are synchronous, so echo
- * transients cannot occur, and waiting the production interval would only
- * slow every repair assertion down.
- */
-const REPAIR_CONFIRM_DELAY =
- // @ts-expect-error - dot notation required for Vite to replace at build time
- process.env.NODE_ENV === 'test' ? 150 : 1000
-
-type PendingRepair = {signature: string; timer: ReturnType}
-const pendingRepairs = new WeakMap()
-
-/**
- * Local edits the editor has emitted but not yet flushed into a mutation.
- * While any exist, the store necessarily lags the editor and a repair diff
- * would "repair away" the user's unflushed keystrokes, so repairs must wait.
- */
-const unflushedEdits = new WeakMap()
-
-function computeRepair(
- editor: Editor,
- remoteValue: PortableTextBlock[],
-): {patches: PtePatch[]; convertible: boolean; signature: string} {
- const snapshot = editor.getSnapshot().context.value
- // The signature covers the full (editor, store) state, not just the diff:
- // with repetitive text, two different transients can produce an identical
- // diff, and a repair must only act when the world actually stood still.
- const stateSignature = JSON.stringify([snapshot, remoteValue])
- try {
- const patches = toEngineSafePatches(
- convertPatches(diffValue(snapshot, remoteValue)),
- remoteValue,
- )
- return {patches, convertible: true, signature: stateSignature}
- } catch {
- // diffValue can emit path shapes the converter does not understand
- // (e.g. array slices when multiple items are dropped). The repair then
- // has to fall back to a whole-value update.
- return {patches: [], convertible: false, signature: `!${stateSignature}`}
- }
-}
-
-function cancelPendingRepair(editor: Editor) {
- const pending = pendingRepairs.get(editor)
- if (pending) {
- clearTimeout(pending.timer)
- pendingRepairs.delete(editor)
- }
-}
-
-function applySync({
- editor,
- getRemoteValue,
-}: {
- editor: Editor
- getRemoteValue: () => PortableTextBlock[] | null | undefined
-}) {
- const remoteValue = getRemoteValue()
-
- if (!remoteValue) {
- return
- }
-
- const first = computeRepair(editor, remoteValue)
- if (first.convertible && first.patches.length === 0) {
- cancelPendingRepair(editor)
- return
- }
-
- if (debug.repair.enabled) {
- debug.repair('editor and store texts diverged %o', {
- editorText: debugTextOf(editor.getSnapshot().context.value),
- remoteText: debugTextOf(remoteValue),
- })
- }
-
- // Same divergence already awaiting confirmation: let that timer decide.
- const pending = pendingRepairs.get(editor)
- if (pending && pending.signature === first.signature) {
- return
- }
- cancelPendingRepair(editor)
-
- const timer = setTimeout(() => {
- pendingRepairs.delete(editor)
-
- // Unflushed local keystrokes mean the store lags the editor by design;
- // a repair now would delete them. Re-arm and wait for the flush (the
- // divergence either disappears once the push round-trips, or persists
- // and gets repaired then).
- if (unflushedEdits.get(editor)) {
- applySync({editor, getRemoteValue})
- return
- }
-
- // Recompute from scratch: the store may have corrected itself (the
- // transient case) or the user may have typed (their edits will push
- // and reconverge through the normal flow); only a divergence that is
- // still byte-for-byte identical is real and safe to repair.
- const latestRemote = getRemoteValue()
- if (!latestRemote) {
- return
- }
- const second = computeRepair(editor, latestRemote)
- if (second.convertible && second.patches.length === 0) {
- return
- }
- if (second.signature !== first.signature) {
- // Still diverged but differently: re-arm so a stable state eventually
- // confirms. Transients converge to the empty diff; genuine divergence
- // stabilizes to a fixed signature within one flush cycle.
- applySync({editor, getRemoteValue})
- return
- }
-
- if (!second.convertible) {
- debug.repair('escalating to whole-value sync (unconvertible diff)')
- editor.send({type: 'update value', value: latestRemote})
- return
- }
-
- const snapshot = editor.getSnapshot().context.value
- debug.repair('applying confirmed repair patches %o', second.patches)
- editor.send({type: 'patches', patches: second.patches, snapshot})
-
- // Patch application is best-effort: the editor skips operations it
- // cannot resolve against its current tree, and concurrent edits to the
- // same range produce keyed operations whose targets no longer exist
- // locally. When the editor is still diverged after the diff-based
- // repair, escalate to the full value sync machinery, which reconciles
- // arbitrary divergence block by block.
- const valueAfterPatches = editor.getSnapshot().context.value
- if (diffValue(valueAfterPatches, latestRemote).length > 0) {
- if (debug.repair.enabled) {
- debug.repair('escalating to whole-value sync %o', {
- editorText: debugTextOf(valueAfterPatches),
- remoteText: debugTextOf(latestRemote),
- })
- }
- editor.send({type: 'update value', value: latestRemote})
- }
- }, REPAIR_CONFIRM_DELAY)
-
- pendingRepairs.set(editor, {signature: first.signature, timer})
-}
-
-const listenToEditor = fromCallback(
- ({sendBack, input}) => {
- const patchSubscription = input.editor.on('patch', () => {
- // Every 'patch' event is a local edit (remote application suppresses
- // patch generation), so the store now lags the editor until the next
- // mutation flush.
- unflushedEdits.set(input.editor, true)
- sendBack({type: 'patch emitted'})
- })
-
- const mutationSubscription = input.editor.on('mutation', (event) => {
- unflushedEdits.set(input.editor, false)
- if (debug.mutation.enabled) {
- debug.mutation('flushed %o', {
- flushText: debugTextOf(event.value),
- snapshotText: debugTextOf(input.editor.getSnapshot().context.value),
- })
- }
- sendBack({
- type: 'mutation flushed',
- value: event.value,
- patches: event.patches,
- })
- })
-
- return () => {
- patchSubscription.unsubscribe()
- mutationSubscription.unsubscribe()
- }
- },
-)
-
-const listenToRemote = fromCallback<
- AnyEventObject,
- {onRemoteValueChange: ValueSyncConfig['onRemoteValueChange']}
->(({sendBack, input}) => {
- return input.onRemoteValueChange(() => {
- sendBack({type: 'remote value changed'})
- })
-})
-
-const listenToRemotePatches = fromCallback<
- AnyEventObject,
- {onRemotePatches: ValueSyncConfig['onRemotePatches']}
->(({sendBack, input}) => {
- return input.onRemotePatches?.((patches) => {
- sendBack({type: 'remote patches received', patches})
- })
-})
-
-/**
- * How long the machine must sit in 'idle' (no local keystrokes, no store
- * events) before the one-shot whole-value repair runs. Long enough for the
- * editor's external value snapshot to catch up after the last flush; short
- * enough that residual divergence from concurrent editing heals promptly.
- */
-const QUIESCENT_REPAIR_DELAY = 500
-
-const valueSyncMachine = setup({
- types: {
- context: {} as {
- editor: Editor
- getRemoteValue: ValueSyncConfig['getRemoteValue']
- onRemoteValueChange: ValueSyncConfig['onRemoteValueChange']
- onRemotePatches: ValueSyncConfig['onRemotePatches']
- },
- input: {} as {
- editor: Editor
- getRemoteValue: ValueSyncConfig['getRemoteValue']
- onRemoteValueChange: ValueSyncConfig['onRemoteValueChange']
- onRemotePatches: ValueSyncConfig['onRemotePatches']
- },
- events: {} as
- | {type: 'patch emitted'}
- | {
- type: 'mutation flushed'
- value: PortableTextBlock[] | undefined
- patches: PtePatch[]
- }
- | {type: 'remote value changed'}
- | {type: 'remote patches received'; patches: PtePatch[]},
- },
- actions: {
- 'send initial value': ({context}) => {
- context.editor.send({
- type: 'update value',
- value: context.getRemoteValue() ?? [],
- })
- },
- 'push to remote': () => {
- throw new Error('push to remote must be provided via .provide()')
- },
- 'apply sync': ({context}) => {
- applySync({
- editor: context.editor,
- getRemoteValue: context.getRemoteValue,
- })
- },
- 'apply remote patches': ({context, event}) => {
- if (event.type !== 'remote patches received') {
- return
- }
- debug.remote('applying remote patches %o', event.patches)
- // The SDK emits `remote-patches` while it is still computing the
- // state update for that transaction, so the store value visible at
- // this moment does not include it yet. The commit lands within the
- // same synchronous task, so after one microtask the store reflects
- // the transaction, whether the event announced a fresh transaction
- // or replayed one the store already had. Only then can the store
- // value serve as the reference for dropping inserts the transaction
- // itself cleaned up again, and as the target for coalescing
- // sidecar-array item operations (which the engine misroutes) into
- // whole-property sets.
- queueMicrotask(() => {
- const snapshot = context.editor.getSnapshot().context.value
- const remoteValue = context.getRemoteValue()
- const coalesced = remoteValue
- ? toEngineSafePatches(event.patches, remoteValue)
- : event.patches
- const patches = filterResolvablePatches(
- remoteValue
- ? filterInsertsMissingFromRemoteValue(coalesced, remoteValue)
- : coalesced,
- snapshot,
- )
- if (patches.length === 0) {
- return
- }
- context.editor.send({type: 'patches', patches, snapshot})
- })
- },
- },
- actors: {
- 'listen to editor': listenToEditor,
- 'listen to remote': listenToRemote,
- 'listen to remote patches': listenToRemotePatches,
- },
-}).createMachine({
- id: 'value sync',
- context: ({input}) => ({
- editor: input.editor,
- getRemoteValue: input.getRemoteValue,
- onRemoteValueChange: input.onRemoteValueChange,
- onRemotePatches: input.onRemotePatches,
- }),
- entry: ['send initial value'],
- invoke: [
- {
- src: 'listen to editor',
- input: ({context}) => ({editor: context.editor}),
- },
- {
- src: 'listen to remote',
- input: ({context}) => ({
- onRemoteValueChange: context.onRemoteValueChange,
- }),
- },
- {
- src: 'listen to remote patches',
- input: ({context}) => ({
- onRemotePatches: context.onRemotePatches,
- }),
- },
- ],
- // Two invariants, learned the hard way:
- //
- // 1. EVERY 'mutation flushed' event must be pushed, in every state. The
- // editor emits mutation events in bursts (one per input batch, e.g.
- // each backspace of a quick delete), and any state without a handler
- // silently drops the flush. A dropped flush permanently diverges the
- // store from the editor, and the whole-value repair then "heals" the
- // editor backwards, resurrecting deleted text.
- // 2. The whole-value repair must only run when no local edits can be in
- // flight (quiescent 'idle'). Running it mid-typing diffs the editor
- // against a store that lags the user's keystrokes and stomps them.
- //
- // Operational patches from other clients still apply immediately in
- // every state; the editor merges them with in-flight local changes.
- initial: 'idle',
- states: {
- 'idle': {
- // One-shot repair after a quiet period. Covers divergence left by
- // best-effort patch application while local edits were in flight
- // (those states never repair; see below) when no further store
- // event arrives to trigger the on-change repair.
- after: {
- [QUIESCENT_REPAIR_DELAY]: {
- actions: ['apply sync'],
- },
- },
- on: {
- 'patch emitted': {
- target: 'local write',
- },
- // Mutation events arrive in bursts (one per input batch), so a
- // flush can land after a sibling flush already advanced the state.
- 'mutation flushed': {
- target: 'pushing to remote',
- actions: ['push to remote'],
- },
- 'remote value changed': {
- actions: ['apply sync'],
- },
- // No immediate repair here: every remote patch batch also updates
- // the store value, so the accompanying 'remote value changed'
- // event runs the whole-value repair right after.
- 'remote patches received': {
- actions: ['apply remote patches'],
- },
- },
- },
- 'local write': {
- on: {
- 'patch emitted': {},
- 'mutation flushed': {
- target: 'pushing to remote',
- actions: ['push to remote'],
- },
- 'remote value changed': {
- target: 'pending sync',
- },
- 'remote patches received': {
- target: 'pending sync',
- actions: ['apply remote patches'],
- },
- },
- },
- 'pushing to remote': {
- on: {
- 'patch emitted': {
- target: 'local write',
- },
- 'mutation flushed': {
- actions: ['push to remote'],
- },
- // No repair on the push acknowledgment: the editor snapshot can
- // lag the live document while the user keeps typing, so a diff
- // against the store here resurrects deleted text and duplicates
- // in-flight keystrokes. Once truly idle, the store change or the
- // quiescent delay runs the repair with a caught-up snapshot.
- 'remote value changed': {
- target: 'idle',
- },
- 'remote patches received': {
- actions: ['apply remote patches'],
- },
- },
- },
- 'pending sync': {
- on: {
- 'patch emitted': {},
- 'mutation flushed': {
- target: 'pushing to remote',
- actions: ['push to remote'],
- },
- 'remote value changed': {},
- 'remote patches received': {
- actions: ['apply remote patches'],
- },
- },
- },
- },
-})
-
-interface SDKValuePluginProps extends DocumentHandle {
- source?: DocumentResource
- path: string
-}
-
-/**
- * The shape of the `remote-patches` document event emitted by
- * `@sanity/sdk` >= 2.17. Declared structurally so the plugin stays
- * compatible with older SDK typings until its dependency is bumped.
- */
-type RemotePatchesDocumentEvent = {
- type: 'remote-patches'
- documentId: string
- transactionId: string
- timestamp: string
- previousRev?: string
- patches: SanityPatchOperations[]
- origin: 'local' | 'remote'
-}
-
-function isRemotePatchesEvent(event: {
- type: string
-}): event is RemotePatchesDocumentEvent {
- return event.type === 'remote-patches'
-}
-
-function getPublishedDocumentId(id: string): string {
- if (id.startsWith('drafts.')) {
- return id.slice('drafts.'.length)
- }
- if (id.startsWith('versions.')) {
- return id.split('.').slice(2).join('.')
- }
- return id
-}
-
-/**
- * @public
- */
-export function SDKValuePlugin(props: SDKValuePluginProps) {
- const normalizedProps = normalizeDocumentHandle(props)
- const {documentId, documentType, path} = normalizedProps
- const setSdkValue = useEditDocument(normalizedProps)
- const instance = useSanityInstance()
- const applyActions = useApplyDocumentActions()
-
- const handle = {documentId, documentType, path}
- const {getCurrent, subscribe} = getDocumentState(
- instance,
- handle,
- )
-
- const onRemotePatches = useCallback(
- (callback: (patches: PtePatch[]) => void) => {
- return subscribeDocumentEvents(instance, {
- eventHandler: (event) => {
- // widen before narrowing: `remote-patches` is not part of the
- // `DocumentEvent` union in older SDK typings
- const candidate: {type: string} = event
- if (!isRemotePatchesEvent(candidate)) {
- return
- }
- // our own transactions are already reflected in the editor
- if (candidate.origin !== 'remote') {
- return
- }
- if (
- getPublishedDocumentId(candidate.documentId) !==
- getPublishedDocumentId(documentId)
- ) {
- return
- }
-
- let patches: PtePatch[] | null
- try {
- patches = scopeRemotePatches(candidate.patches, path)
- } catch {
- // unconvertible patch shapes fall back to the whole-value sync
- // driven by `onRemoteValueChange`
- return
- }
- if (patches && patches.length > 0) {
- callback(patches)
- }
- },
- })
- },
- [instance, documentId, path],
- )
-
- const pushPatches = useCallback(
- (patches: PtePatch[]) => {
- const sanityPatches = convertPatchesToSanity(patches, {prefix: path})
- // `preserveOperations` ships in @sanity/sdk >= 2.17; the intersection
- // type keeps the plugin compatible with older SDK typings
- const action: EditDocumentAction & {preserveOperations?: boolean} = {
- ...editDocument(
- {documentId, documentType},
- sanityPatches as Parameters[1],
- ),
- preserveOperations: true,
- }
- applyActions(action)
- },
- [applyActions, documentId, documentType, path],
- )
-
- return (
-
- )
-}
-
-/**
- * @internal
- */
-type ValueSyncConfig = {
- getRemoteValue: () => PortableTextBlock[] | null | undefined
- pushValue: (value: PortableTextBlock[]) => void
- onRemoteValueChange: (callback: () => void) => () => void
- /**
- * Optional patch channel. When provided, operational patches from other
- * clients are applied directly to the editor (in every state) instead of
- * waiting for a whole-value diff, and local editor patches are pushed
- * through `pushPatches`. The whole-value sync remains as a fallback for
- * anything the patch channel cannot express.
- */
- onRemotePatches?: (
- callback: (patches: PtePatch[]) => void,
- ) => (() => void) | undefined
- /**
- * Pushes the editor's own operational patches to the remote store. May
- * throw when a patch cannot be converted, in which case the plugin falls
- * back to pushing the whole value.
- */
- pushPatches?: (patches: PtePatch[]) => void
-}
-
-/**
- * NOTE: You are probably looking for SDKValuePlugin instead of this.
- * This is a lower-level plugin that only handles syncing the value
- * between the editor and a remote source. It does not know anything
- * about Sanity documents or how to fetch/update them.
- *
- * May be removed in the future, do not rely on this directly.
- *
- * @internal
- */
-export function ValueSyncPlugin(props: ValueSyncConfig) {
- const {
- getRemoteValue,
- pushValue,
- onRemoteValueChange,
- onRemotePatches,
- pushPatches,
- } = props
- const editor = useEditor()
-
- useActorRef(
- valueSyncMachine.provide({
- actions: {
- 'push to remote': ({context, event}) => {
- if (event.type !== 'mutation flushed') {
- return
- }
-
- if (pushPatches && event.patches.length > 0) {
- try {
- const mergeable = toMergeableMarkDefsPatches(
- event.patches,
- context.getRemoteValue,
- )
- debug.push('pushing patches %o', mergeable)
- pushPatches(mergeable)
- return
- } catch {
- // fall back to pushing the whole value below
- }
- }
-
- if (debug.push.enabled) {
- debug.push(
- 'pushing whole value %s',
- debugTextOf(
- event.value ?? context.editor.getSnapshot().context.value,
- ),
- )
- }
- pushValue(event.value ?? context.editor.getSnapshot().context.value)
- },
- },
- }),
- {
- input: {
- editor,
- getRemoteValue,
- onRemoteValueChange,
- onRemotePatches,
- },
- },
- )
-
- return null
-}
diff --git a/packages/plugin-sdk-value/src/plugin.two-client.test.tsx b/packages/plugin-sdk-value/src/plugin.two-client.test.tsx
deleted file mode 100644
index 1d0136b790..0000000000
--- a/packages/plugin-sdk-value/src/plugin.two-client.test.tsx
+++ /dev/null
@@ -1,355 +0,0 @@
-import type {Editor, Patch as PtePatch} from '@portabletext/editor'
-import {EditorProvider, PortableTextEditable} from '@portabletext/editor'
-import {EditorRefPlugin} from '@portabletext/editor/plugins'
-import {applyAll} from '@portabletext/patches'
-import {defineSchema, type PortableTextBlock} from '@portabletext/schema'
-import {createRef} from 'react'
-import {afterEach, describe, expect, test, vi} from 'vitest'
-import {render} from 'vitest-browser-react'
-import {page} from 'vitest/browser'
-import {ValueSyncPlugin} from './plugin.sdk-value'
-
-/**
- * A shared "server" connecting two clients, mimicking the SDK's document
- * store semantics:
- *
- * - a client's own patches apply to its local value optimistically and
- * synchronously
- * - deliveries to the server are queued; `deliver()` applies a queued
- * transaction to the server value best-effort (json-match semantics:
- * patches whose paths don't resolve are no-ops), rebases every client's
- * local value onto the server truth, and forwards the raw patches to the
- * other client's patch channel
- */
-function createTwoClientServer(initialValue: PortableTextBlock[]) {
- let serverValue = initialValue
-
- type PendingTransaction =
- | {kind: 'patches'; patches: PtePatch[]}
- | {kind: 'value'; value: PortableTextBlock[]}
-
- type ClientChannels = {
- pending: PendingTransaction[]
- valueSubscriber: (() => void) | null
- patchSubscriber: ((patches: PtePatch[]) => void) | null
- }
-
- const clients: [ClientChannels, ClientChannels] = [
- {pending: [], valueSubscriber: null, patchSubscriber: null},
- {pending: [], valueSubscriber: null, patchSubscriber: null},
- ]
-
- const pendingDeliveries: Array<() => void> = []
-
- function applyBestEffort(
- value: PortableTextBlock[],
- patches: PtePatch[],
- ): PortableTextBlock[] {
- let next = value
- for (const patch of patches) {
- try {
- next = applyAll(next, [patch])
- } catch {
- // the server no-ops patches whose paths don't resolve
- }
- }
- return next
- }
-
- // A client's local value is the server truth with its own unacknowledged
- // transactions rebased on top, like the SDK's optimistic document store
- function localValue(client: ClientChannels): PortableTextBlock[] {
- return client.pending.reduce(
- (value, transaction) =>
- transaction.kind === 'value'
- ? transaction.value
- : applyBestEffort(value, transaction.patches),
- serverValue,
- )
- }
-
- function createStore(index: 0 | 1) {
- const client = clients[index]
- const other = clients[index === 0 ? 1 : 0]
-
- return {
- getRemoteValue: () => localValue(client),
- onRemoteValueChange: (callback: () => void) => {
- client.valueSubscriber = callback
- return () => {
- client.valueSubscriber = null
- }
- },
- onRemotePatches: (callback: (patches: PtePatch[]) => void) => {
- client.patchSubscriber = callback
- return () => {
- client.patchSubscriber = null
- }
- },
- pushValue: vi.fn((newValue: PortableTextBlock[]) => {
- const transaction: PendingTransaction = {kind: 'value', value: newValue}
- client.pending.push(transaction)
- client.valueSubscriber?.()
- pendingDeliveries.push(() => {
- serverValue = newValue
- client.pending.splice(client.pending.indexOf(transaction), 1)
- other.valueSubscriber?.()
- client.valueSubscriber?.()
- })
- }),
- pushPatches: vi.fn((patches: PtePatch[]) => {
- const transaction: PendingTransaction = {kind: 'patches', patches}
- client.pending.push(transaction)
- client.valueSubscriber?.()
- pendingDeliveries.push(() => {
- serverValue = applyBestEffort(serverValue, patches)
- client.pending.splice(client.pending.indexOf(transaction), 1)
- other.patchSubscriber?.(patches)
- other.valueSubscriber?.()
- client.valueSubscriber?.()
- })
- }),
- }
- }
-
- return {
- storeA: createStore(0),
- storeB: createStore(1),
- getServerValue: () => serverValue,
- hasPendingDeliveries: () => pendingDeliveries.length > 0,
- deliver: () => {
- while (pendingDeliveries.length > 0) {
- pendingDeliveries.shift()!()
- }
- },
- }
-}
-
-type Server = ReturnType
-type Store = Server['storeA']
-
-const schemaDefinition = defineSchema({
- decorators: [{name: 'strong'}, {name: 'em'}],
- annotations: [{name: 'link', fields: [{name: 'href', type: 'string'}]}],
-})
-
-async function renderTwoClients(server: Server) {
- const editorARef = createRef()
- const editorBRef = createRef()
-
- const client = (ref: React.Ref, store: Store, testId: string) => (
-
-
-
-
-
- )
-
- const result = await render(
- <>
- {client(editorARef, server.storeA, 'client-a')}
- {client(editorBRef, server.storeB, 'client-b')}
- >,
- )
-
- await vi.waitFor(() => {
- expect(editorARef.current).toBeTruthy()
- expect(editorBRef.current).toBeTruthy()
- })
-
- return {
- editorA: editorARef.current!,
- editorB: editorBRef.current!,
- locatorA: page.getByTestId('client-a'),
- locatorB: page.getByTestId('client-b'),
- unmount: result.unmount,
- }
-}
-
-function makeBlock(key: string, text: string): PortableTextBlock {
- return {
- _type: 'block',
- _key: key,
- children: [{_type: 'span', _key: `${key}-span`, text, marks: []}],
- markDefs: [],
- style: 'normal',
- }
-}
-
-function selectRange(
- editor: Editor,
- blockKey: string,
- spanKey: string,
- anchorOffset: number,
- focusOffset: number,
-) {
- editor.send({
- type: 'select',
- at: {
- anchor: {
- path: [{_key: blockKey}, 'children', {_key: spanKey}],
- offset: anchorOffset,
- },
- focus: {
- path: [{_key: blockKey}, 'children', {_key: spanKey}],
- offset: focusOffset,
- },
- },
- })
-}
-
-async function settleAndAssertConvergence(options: {
- server: Server
- editorA: Editor
- editorB: Editor
-}) {
- const {server, editorA, editorB} = options
-
- await vi.waitFor(
- () => {
- server.deliver()
- expect(server.hasPendingDeliveries()).toBe(false)
- expect(editorA.getSnapshot().context.value).toEqual(
- server.getServerValue(),
- )
- expect(editorB.getSnapshot().context.value).toEqual(
- server.getServerValue(),
- )
- },
- {timeout: 5000, interval: 100},
- )
-}
-
-describe('two clients through a shared patch-channel store', () => {
- let cleanup: (() => void) | undefined
- let consoleError: ReturnType | undefined
-
- afterEach(() => {
- cleanup?.()
- cleanup = undefined
- consoleError?.mockRestore()
- consoleError = undefined
- })
-
- test('Scenario: concurrent typing in different blocks converges without data loss', async () => {
- const server = createTwoClientServer([
- makeBlock('b1', 'alpha'),
- makeBlock('b2', 'omega'),
- ])
- const {editorA, editorB, locatorA, locatorB, unmount} =
- await renderTwoClients(server)
- cleanup = unmount
-
- await locatorA.click()
- selectRange(editorA, 'b1', 'b1-span', 5, 5)
- editorA.send({type: 'insert.text', text: ' one'})
- await locatorB.click()
- selectRange(editorB, 'b2', 'b2-span', 5, 5)
- editorB.send({type: 'insert.text', text: ' two'})
-
- await vi.waitFor(() => {
- expect(server.storeA.pushPatches).toHaveBeenCalled()
- expect(server.storeB.pushPatches).toHaveBeenCalled()
- })
-
- await settleAndAssertConvergence({server, editorA, editorB})
-
- const texts = server
- .getServerValue()
- .map((block) =>
- ((block as {children?: Array<{text?: string}>}).children ?? [])
- .map((child) => child.text ?? '')
- .join(''),
- )
- expect(texts).toEqual(['alpha one', 'omega two'])
- })
-
- test('Scenario: concurrent same-range bolding converges', async () => {
- // Both clients bold overlapping parts of the same span at the same
- // moment. The engine cannot apply the other side's split operations
- // (its keyed targets are gone locally), so this exercises the repair
- // path end to end.
- consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
- const server = createTwoClientServer([makeBlock('b1', 'Hello world')])
- const {editorA, editorB, locatorA, locatorB, unmount} =
- await renderTwoClients(server)
- cleanup = unmount
-
- await locatorA.click()
- selectRange(editorA, 'b1', 'b1-span', 0, 8)
- editorA.send({type: 'decorator.add', decorator: 'strong'})
- await locatorB.click()
- selectRange(editorB, 'b1', 'b1-span', 4, 11)
- editorB.send({type: 'decorator.add', decorator: 'strong'})
-
- await vi.waitFor(() => {
- expect(server.storeA.pushPatches).toHaveBeenCalled()
- expect(server.storeB.pushPatches).toHaveBeenCalled()
- })
-
- await settleAndAssertConvergence({server, editorA, editorB})
- })
-
- test('Scenario: concurrent link and bold over overlapping ranges converge', async () => {
- // The rig's link-overlap-range scenario: one client annotates while the
- // other bolds an overlapping range. markDefs is written as a whole-array
- // set, so this also exercises sidecar-array conflicts.
- consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
- const server = createTwoClientServer([makeBlock('b1', 'Hello world')])
- const {editorA, editorB, locatorA, locatorB, unmount} =
- await renderTwoClients(server)
- cleanup = unmount
-
- await locatorA.click()
- selectRange(editorA, 'b1', 'b1-span', 0, 8)
- editorA.send({
- type: 'annotation.add',
- annotation: {name: 'link', value: {href: 'https://example.com'}},
- })
- await locatorB.click()
- selectRange(editorB, 'b1', 'b1-span', 4, 11)
- editorB.send({type: 'decorator.add', decorator: 'strong'})
-
- await vi.waitFor(() => {
- expect(server.storeA.pushPatches).toHaveBeenCalled()
- expect(server.storeB.pushPatches).toHaveBeenCalled()
- })
-
- await settleAndAssertConvergence({server, editorA, editorB})
- })
-
- test('Scenario: a formatting conflict during concurrent typing converges', async () => {
- // The hardest mix: one client types while the other formats the range
- // being typed into.
- consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
- const server = createTwoClientServer([makeBlock('b1', 'Hello world')])
- const {editorA, editorB, locatorA, locatorB, unmount} =
- await renderTwoClients(server)
- cleanup = unmount
-
- await locatorA.click()
- selectRange(editorA, 'b1', 'b1-span', 11, 11)
- editorA.send({type: 'insert.text', text: ' and more'})
- await locatorB.click()
- selectRange(editorB, 'b1', 'b1-span', 0, 11)
- editorB.send({type: 'decorator.add', decorator: 'strong'})
-
- await vi.waitFor(() => {
- expect(server.storeA.pushPatches).toHaveBeenCalled()
- expect(server.storeB.pushPatches).toHaveBeenCalled()
- })
-
- await settleAndAssertConvergence({server, editorA, editorB})
- })
-})
diff --git a/packages/plugin-sdk-value/src/plugin.value-sync.test.tsx b/packages/plugin-sdk-value/src/plugin.value-sync.test.tsx
deleted file mode 100644
index 26c2ac9d2c..0000000000
--- a/packages/plugin-sdk-value/src/plugin.value-sync.test.tsx
+++ /dev/null
@@ -1,1160 +0,0 @@
-import type {Editor, Patch as PtePatch} from '@portabletext/editor'
-import {EditorProvider, PortableTextEditable} from '@portabletext/editor'
-import {EditorRefPlugin} from '@portabletext/editor/plugins'
-import {toTextspec} from '@portabletext/editor/test'
-import {applyAll, type JSONValue} from '@portabletext/patches'
-import {defineSchema, type PortableTextBlock} from '@portabletext/schema'
-import {createTestKeyGenerator} from '@portabletext/test'
-import {createRef} from 'react'
-import {afterEach, describe, expect, test, vi} from 'vitest'
-import {render} from 'vitest-browser-react'
-import {page, userEvent} from 'vitest/browser'
-import {ValueSyncPlugin} from './plugin.sdk-value'
-
-// ---- Mock value store ----
-
-function createMockValueStore(initialValue: PortableTextBlock[] = []) {
- let value = initialValue
- let subscriber: (() => void) | null = null
-
- const pushValue = vi.fn((newValue: PortableTextBlock[]) => {
- value = newValue
- // Fire subscriber synchronously, like the real SDK (Zustand + RxJS)
- subscriber?.()
- })
-
- return {
- getRemoteValue: () => value,
- pushValue,
- onRemoteValueChange: (callback: () => void) => {
- subscriber = callback
- return () => {
- subscriber = null
- }
- },
- getValue: () => value,
- // Simulate a remote change (updates value and notifies subscriber)
- setRemoteValue: (newValue: PortableTextBlock[]) => {
- value = newValue
- subscriber?.()
- },
- }
-}
-
-type MockStore = ReturnType
-
-/**
- * A mock store with a patch channel, mirroring an SDK that emits
- * `remote-patches` document events and accepts preserved patch operations.
- */
-function createMockPatchStore(initialValue: PortableTextBlock[] = []) {
- let value = initialValue
- let valueSubscriber: (() => void) | null = null
- let patchSubscriber: ((patches: PtePatch[]) => void) | null = null
-
- const pushValue = vi.fn((newValue: PortableTextBlock[]) => {
- value = newValue
- valueSubscriber?.()
- })
-
- const pushPatches = vi.fn((patches: PtePatch[]) => {
- value = applyAll(value, patches)
- valueSubscriber?.()
- })
-
- return {
- getRemoteValue: () => value,
- pushValue,
- pushPatches,
- onRemoteValueChange: (callback: () => void) => {
- valueSubscriber = callback
- return () => {
- valueSubscriber = null
- }
- },
- onRemotePatches: (callback: (patches: PtePatch[]) => void) => {
- patchSubscriber = callback
- return () => {
- patchSubscriber = null
- }
- },
- getValue: () => value,
- // Simulate a transaction arriving from another client. Mirrors the real
- // SDK's ordering: the `remote-patches` event fires while the SDK is still
- // computing the state update for that transaction, so subscribers observe
- // the pre-transaction value during the event; the value commit and its
- // notification follow. Application is best-effort per patch, mirroring
- // the server's json-match semantics where patches whose paths don't
- // resolve are no-ops.
- receiveRemotePatches: (patches: PtePatch[]) => {
- patchSubscriber?.(patches)
- for (const patch of patches) {
- try {
- value = applyAll(value, [patch])
- } catch {
- // the server would no-op this patch
- }
- }
- valueSubscriber?.()
- },
- // Simulate a remote transaction whose patches don't resolve against this
- // client's state: the server still applied it (it had the sender's view
- // of the document), so the store value jumps to `newValue`, while the raw
- // `patches` are what travels over the patch channel.
- receiveRemoteTransaction: (
- newValue: PortableTextBlock[],
- patches: PtePatch[],
- ) => {
- value = newValue
- patchSubscriber?.(patches)
- valueSubscriber?.()
- },
- }
-}
-
-type MockPatchStore = ReturnType
-
-// ---- Test editor helper ----
-
-async function createSyncedEditor(options: {
- initialValue?: PortableTextBlock[]
- store: MockStore | MockPatchStore | Omit
- schemaDefinition?: ReturnType
-}) {
- const editorRef = createRef()
- const keyGenerator = createTestKeyGenerator()
- const {store} = options
-
- const result = await render(
-
-
-
-
- ,
- )
-
- const locator = page.getByRole('textbox')
- await expect.element(locator).toBeInTheDocument()
-
- return {
- editor: editorRef.current!,
- locator,
- unmount: result.unmount,
- }
-}
-
-// ---- Helpers ----
-
-function makeBlock(
- key: string,
- text: string,
- spanKey = `${key}-span`,
-): PortableTextBlock {
- return {
- _type: 'block',
- _key: key,
- children: [{_type: 'span', _key: spanKey, text, marks: []}],
- markDefs: [],
- style: 'normal',
- }
-}
-
-function typedBlock(text: string): PortableTextBlock {
- return {
- _type: 'block',
- _key: 'k2',
- children: [{_type: 'span', _key: 'k3', text, marks: []}],
- markDefs: [],
- style: 'normal',
- }
-}
-
-const TIMERS: Array<
- 'setTimeout' | 'clearTimeout' | 'setInterval' | 'clearInterval'
-> = ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval']
-
-function getEditorText(editor: Editor): string {
- return toTextspec(editor.getSnapshot().context)
-}
-
-// ---- Tests ----
-
-describe(ValueSyncPlugin.name, () => {
- let cleanup: (() => void) | undefined
-
- afterEach(() => {
- cleanup?.()
- cleanup = undefined
- vi.useRealTimers()
- })
-
- describe('initial value', () => {
- test('Scenario: the editor starts with the initial value from the store', async () => {
- const store = createMockValueStore([makeBlock('b1', 'Hello')])
- const {editor, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: Hello')
- })
- })
-
- test('Scenario: an empty store starts the editor empty', async () => {
- const store = createMockValueStore([])
- const {editor, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: |')
- })
- })
- })
-
- describe('local edits push to store', () => {
- test('Scenario: typing pushes the value to the store after the mutation flush', async () => {
- const store = createMockValueStore()
- const {editor, locator, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await locator.click()
- editor.send({type: 'insert.text', text: 'Hello'})
-
- await vi.waitFor(() => {
- expect(store.pushValue).toHaveBeenCalled()
- })
-
- const pushedValue = store.pushValue.mock.lastCall?.[0] ?? []
- expect(
- toTextspec({
- value: pushedValue,
- schema: editor.getSnapshot().context.schema,
- selection: null,
- }),
- ).toEqual('B: Hello')
- })
-
- test('a flush landing while a push awaits acknowledgement is pushed', async () => {
- vi.useFakeTimers({toFake: TIMERS})
- const store = createMockValueStore()
- const {editor, locator, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: |')
- })
- await userEvent.click(locator)
-
- const pushedValues: Array = []
- store.pushValue.mockImplementation((value: PortableTextBlock[]) => {
- pushedValues.push(value)
- })
-
- await userEvent.type(locator, 'abc')
- await userEvent.keyboard('{Backspace}')
- await vi.advanceTimersByTimeAsync(250)
-
- expect(pushedValues).toEqual([[typedBlock('ab')], [typedBlock('ab')]])
-
- store.setRemoteValue(pushedValues.at(-1)!)
- await vi.advanceTimersByTimeAsync(1000)
-
- expect(getEditorText(editor)).toEqual('B: ab|')
- })
- })
-
- describe('solo typing fidelity', () => {
- // Field regression: a single user typing with delete-and-retype bursts
- // saw text reordered and duplicated. Two machine bugs compounded:
- // 'mutation flushed' events arriving in bursts were dropped by states
- // without a handler (their patches never pushed, so the store diverged),
- // and the whole-value repair ran while local edits were in flight,
- // diffing the editor against the diverged store and resurrecting
- // deleted text. This test types in bursts that straddle flush timing
- // and requires the editor, the store, and the expected text to agree.
- test('Scenario: delete-and-retype bursts converge to exactly what was typed', async () => {
- vi.useFakeTimers({toFake: TIMERS})
- const store = createMockPatchStore([])
- const {editor, locator, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: |')
- })
- // Real key events matter here: each keystroke is its own operation,
- // so a flush emits one mutation event per pending operation — the
- // burst that used to hit states without a 'mutation flushed' handler.
- // `editor.send` events coalesce into a single bulk and cannot
- // reproduce the burst.
- await userEvent.click(locator)
-
- const settle = (ms: number) => vi.advanceTimersByTimeAsync(ms)
- const backspace = async (count: number) => {
- for (let i = 0; i < count; i++) {
- await userEvent.keyboard('{Backspace}')
- }
- }
-
- // Interleave typing, deletes, and retypes across flush windows (the
- // test-mode flush interval is 500ms, the typing debounce 250ms)
- // without waiting for convergence in between.
- await userEvent.type(locator, 'publish editors ')
- await settle(300)
- await userEvent.type(locator, 'deadline ')
- await backspace(5)
- await settle(120)
- await userEvent.type(locator, 'line ')
- await settle(300)
- await userEvent.type(locator, 'sources ')
- await backspace(8)
- await settle(550)
- await userEvent.type(locator, 'sources ')
- await userEvent.type(locator, 'context')
- await settle(120)
- await backspace(3)
- await settle(300)
- await userEvent.type(locator, 'ext')
- await settle(2000)
-
- expect(getEditorText(editor)).toEqual(
- 'B: publish editors deadline sources context|',
- )
- expect(
- toTextspec({
- value: store.getValue(),
- schema: editor.getSnapshot().context.schema,
- selection: null,
- }),
- ).toEqual('B: publish editors deadline sources context')
- // The explicit test timeout is generous because the bursts above are
- // ~70 real key events, each a round-trip to the browser whose cost
- // scales with machine load: the interaction takes ~3s idle but has
- // measured ~13s on CI, close to vitest's 15s default.
- }, 60_000)
- })
-
- describe('remote changes apply to editor', () => {
- test('Scenario: a remote change updates the idle editor', async () => {
- const store = createMockValueStore()
- const {editor, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- store.setRemoteValue([makeBlock('b1', 'Hello from remote')])
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: Hello from remote')
- })
- })
-
- // Field regression: when a collaborator's transaction arrives
- // interleaved with the listener echoes of this client's own recent
- // edits, the store value is transiently wrong until the rebase
- // corrects it. A repair fired inside that window used to copy the
- // transient into the editor and a follow-up repair restored the text
- // at a drifted offset, scrambling words typed in the meantime. The
- // repair must wait out the blink and only act on divergence that
- // persists.
- test('Scenario: a transiently wrong store value is never copied into the editor', async () => {
- vi.useFakeTimers({toFake: TIMERS})
- const store = createMockValueStore([makeBlock('b1', 'stable text here')])
- const {editor, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: stable text here')
- })
-
- // A whipsaw self-heals by the end (the second repair restores the
- // text), so final-state assertions cannot catch it; in production the
- // user types between the two repairs and the restore lands at a
- // drifted offset. The direct observable is the repair traffic itself:
- // a transient must produce ZERO sync writes into the editor.
- const syncWrites: Array = []
- const originalSend = editor.send.bind(editor)
- editor.send = ((event: Parameters[0]) => {
- if (event.type === 'patches' || event.type === 'update value') {
- syncWrites.push(event.type)
- }
- originalSend(event)
- }) as Editor['send']
-
- try {
- // The store blinks: a wrong value (own edits double-applied) that
- // self-corrects shortly after, well inside the confirmation window.
- store.setRemoteValue([makeBlock('b1', 'stable tex')])
- await vi.advanceTimersByTimeAsync(50)
- store.setRemoteValue([makeBlock('b1', 'stable text here')])
-
- // Wait past the confirmation window.
- await vi.advanceTimersByTimeAsync(400)
- } finally {
- editor.send = originalSend
- }
-
- expect(getEditorText(editor)).toEqual('B: stable text here')
- expect(syncWrites).toEqual([])
- })
-
- test('Scenario: a persistent divergence still gets repaired', async () => {
- const store = createMockValueStore([makeBlock('b1', 'before')])
- const {editor, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: before')
- })
-
- // A real remote change: it persists, so after the confirmation
- // window the repair applies it.
- store.setRemoteValue([makeBlock('b1', 'after, and it stays')])
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: after, and it stays')
- })
- })
-
- test('Scenario: a remote decorator toggle syncs `marks` inserts and unsets', async () => {
- const makeValue = (marks: string[]): PortableTextBlock[] => [
- {
- _type: 'block',
- _key: 'b1',
- children: [{_type: 'span', _key: 's1', text: 'Hello', marks}],
- markDefs: [],
- style: 'normal',
- },
- ]
-
- const store = createMockValueStore(makeValue([]))
- const {editor, unmount} = await createSyncedEditor({
- store,
- schemaDefinition: defineSchema({decorators: [{name: 'strong'}]}),
- })
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: Hello')
- })
-
- // A collaborator toggles bold on. `applySync` diffs this into an
- // `insert` after `marks[-1]`.
- store.setRemoteValue(makeValue(['strong']))
-
- await vi.waitFor(() => {
- expect(editor.getSnapshot().context.value).toEqual(
- makeValue(['strong']),
- )
- })
-
- // The collaborator toggles bold back off. `applySync` diffs this
- // into an `unset` of `marks[0]`.
- store.setRemoteValue(makeValue([]))
-
- await vi.waitFor(() => {
- expect(editor.getSnapshot().context.value).toEqual(makeValue([]))
- })
- })
-
- test('Scenario: a remote annotation toggle syncs span splits, `marks` and `markDefs`', async () => {
- const plainValue: PortableTextBlock[] = [
- {
- _type: 'block',
- _key: 'b1',
- children: [
- {_type: 'span', _key: 's1', text: 'hello world', marks: []},
- ],
- markDefs: [],
- style: 'normal',
- },
- ]
- const annotatedValue: PortableTextBlock[] = [
- {
- _type: 'block',
- _key: 'b1',
- children: [
- {_type: 'span', _key: 's1', text: 'hello ', marks: []},
- {_type: 'span', _key: 's2', text: 'wor', marks: ['m1']},
- {_type: 'span', _key: 's3', text: 'ld', marks: []},
- ],
- markDefs: [{_key: 'm1', _type: 'link', href: 'https://sanity.io'}],
- style: 'normal',
- },
- ]
-
- const store = createMockValueStore(plainValue)
- const {editor, unmount} = await createSyncedEditor({
- store,
- schemaDefinition: defineSchema({
- annotations: [
- {name: 'link', fields: [{name: 'href', type: 'string'}]},
- ],
- }),
- })
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: hello world')
- })
-
- // A collaborator applies a link to "wor": the span splits in three,
- // the middle one referencing a new markDef.
- store.setRemoteValue(annotatedValue)
-
- await vi.waitFor(() => {
- expect(editor.getSnapshot().context.value).toEqual(annotatedValue)
- })
-
- // The collaborator removes the link again: spans merge back and the
- // markDef is removed.
- store.setRemoteValue(plainValue)
-
- await vi.waitFor(() => {
- expect(editor.getSnapshot().context.value).toEqual(plainValue)
- })
- })
- })
-
- describe('echo suppression', () => {
- test('Scenario: an echo after a local edit does not revert the editor', async () => {
- const store = createMockValueStore()
- const {editor, locator, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await locator.click()
- editor.send({type: 'insert.text', text: 'Hello'})
-
- // Wait for the value to push to the store
- await vi.waitFor(() => {
- expect(store.pushValue).toHaveBeenCalled()
- })
-
- // The synchronous echo from pushValue should have been absorbed
- // by the "pushing to remote" state. The editor should still
- // have the correct value.
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: Hello|')
- })
- })
-
- test('Scenario: an echo with normalization divergence does not revert the editor', async () => {
- const store = createMockValueStore()
- const {editor, locator, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await locator.click()
- editor.send({type: 'insert.text', text: 'Hello'})
-
- // Make pushValue store a slightly different value (normalization divergence)
- store.pushValue.mockImplementationOnce((value: PortableTextBlock[]) => {
- const divergent = value.map((block) => {
- const {markDefs: _markDefs, ...rest} = block as PortableTextBlock & {
- markDefs: unknown
- }
- return rest
- })
- store.setRemoteValue(divergent as PortableTextBlock[])
- })
-
- // Wait for mutation flush
- await vi.waitFor(() => {
- expect(store.pushValue).toHaveBeenCalled()
- })
-
- // Editor should still have the correct value, not reverted
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: Hello|')
- })
- })
- })
-
- describe('stale sync prevention', () => {
- test('Scenario: a stale remote value during typing does not revert the editor', async () => {
- vi.useFakeTimers({toFake: TIMERS})
- const store = createMockValueStore()
- const {editor, locator, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await locator.click()
- editor.send({type: 'insert.text', text: 'Hello'})
-
- await vi.advanceTimersByTimeAsync(250)
- expect(store.pushValue).toHaveBeenCalledTimes(1)
- store.pushValue.mockClear()
-
- editor.send({type: 'insert.text', text: ' world'})
-
- // Simulate stale remote callback (e.g., Content Lake acknowledged
- // the first mutation, WebSocket reconnect delivers old value)
- store.setRemoteValue([makeBlock('stale', 'Hello')])
-
- // Editor should NOT revert to "Hello" — it has pending writes.
- await vi.advanceTimersByTimeAsync(249)
- expect(store.pushValue).not.toHaveBeenCalled()
- expect(getEditorText(editor)).toEqual('B: Hello world|')
-
- await vi.advanceTimersByTimeAsync(1)
- expect(store.pushValue).toHaveBeenCalledTimes(1)
-
- // After mutation flush, editor should have the full text
- await vi.advanceTimersByTimeAsync(1000)
- expect(getEditorText(editor)).toEqual('B: Hello world|')
- })
-
- test('Scenario: a remote change during a local write applies after the flush', async () => {
- const store = createMockValueStore()
- const {editor, locator, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await locator.click()
- editor.send({type: 'insert.text', text: 'Hello'})
-
- await vi.waitFor(() => {
- expect(store.pushValue).toHaveBeenCalled()
- })
- store.pushValue.mockClear()
-
- // When the mutation flushes and pushValue is called, simulate the
- // server merging our value with the concurrent remote change
- store.pushValue.mockImplementationOnce(
- (newValue: PortableTextBlock[]) => {
- store.setRemoteValue([
- ...(newValue as PortableTextBlock[]),
- makeBlock('remote-1', 'from remote'),
- ])
- },
- )
-
- // Insert text — the patch fires synchronously (machine enters
- // `local write`) but the mutation flush is asynchronous
- editor.send({type: 'insert.text', text: ' world'})
-
- // A remote change arrives while the machine is in `local write`,
- // pushing it into `pending sync`
- store.setRemoteValue([
- ...store.getValue(),
- makeBlock('remote-1', 'from remote'),
- ])
-
- // Wait for mutation flush
- await vi.waitFor(() => {
- expect(store.pushValue).toHaveBeenCalled()
- })
-
- // `pending sync` defers the sync until after the push. The deferred
- // sync should detect the remote block and apply it.
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual(
- ['B: Hello world|', 'B: from remote'].join('\n'),
- )
- })
- })
-
- test('Scenario: a remote change without pending writes applies immediately', async () => {
- const store = createMockValueStore()
- const {editor, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- store.setRemoteValue([makeBlock('b1', 'Hello from remote')])
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: Hello from remote')
- })
- })
- })
-
- describe('patch channel', () => {
- test('Scenario: remote patches apply to the editor', async () => {
- const store = createMockPatchStore([makeBlock('b1', 'Hello')])
- const {editor, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: Hello')
- })
-
- store.receiveRemotePatches([
- {
- type: 'insert',
- origin: 'remote',
- position: 'after',
- path: [{_key: 'b1'}],
- items: [makeBlock('b2', 'From remote')] as unknown as JSONValue[],
- },
- ])
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual(
- ['B: Hello', 'B: From remote'].join('\n'),
- )
- })
- // the patch was applied operationally; no whole-value push happened
- expect(store.pushValue).not.toHaveBeenCalled()
- })
-
- test('Scenario: a staging span absent from the remote value is never rendered', async () => {
- const initialValue = [makeBlock('b1', 'A: ')]
- const finalValue = [makeBlock('b1', 'A: ALPHA')]
- const store = createMockPatchStore(initialValue)
- const {editor, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: A: ')
- })
-
- store.receiveRemoteTransaction(finalValue, [
- {
- type: 'insert',
- origin: 'remote',
- position: 'after',
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}],
- items: [
- {
- _type: 'span',
- _key: 'staging-span',
- text: 'ALPHA',
- marks: [],
- },
- ] as unknown as JSONValue[],
- },
- {
- type: 'diffMatchPatch',
- origin: 'remote',
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}, 'text'],
- value: '@@ -1,3 +1,8 @@\n A: \n+ALPHA\n',
- },
- ])
-
- // patch application waits one microtask for the store commit
- await Promise.resolve()
-
- expect(getEditorText(editor)).toEqual('B: A: ALPHA')
- })
-
- test('Scenario: a remote mid-span decorator toggle applies without a transient flash', async () => {
- // Field regression: editor A bolds the word "before" in the middle of
- // a span; on editor B the word vanished ("…quarterly report dawn.")
- // for a beat before the whole-value repair restored it. The patches
- // below are the bold transaction as a real editor emits it: two text
- // shrinks on the original span, two inserts of the split-off spans,
- // then a `marks` set on the new middle span. The SDK emits the
- // `remote-patches` event while it is still computing the state update
- // for the transaction, so the store value does not reflect it during
- // the event; filtering the inserts against that stale value dropped
- // the new spans while the text shrinks still applied.
- const text =
- 'ALPHA The newsroom shipped its quarterly report before dawn.'
- const store = createMockPatchStore([makeBlock('b1', text)])
- const {editor, unmount} = await createSyncedEditor({
- store,
- schemaDefinition: defineSchema({decorators: [{name: 'strong'}]}),
- })
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual(`B: ${text}`)
- })
-
- store.receiveRemotePatches([
- {
- type: 'diffMatchPatch',
- origin: 'remote',
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}, 'text'],
- value: '@@ -51,10 +51,4 @@\n fore\n- dawn.\n',
- },
- {
- type: 'setIfMissing',
- origin: 'remote',
- path: [{_key: 'b1'}, 'children'],
- value: [],
- },
- {
- type: 'insert',
- origin: 'remote',
- position: 'after',
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}],
- items: [
- {_type: 'span', _key: 's-dawn', marks: [], text: ' dawn.'},
- ] as unknown as JSONValue[],
- },
- {
- type: 'diffMatchPatch',
- origin: 'remote',
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}, 'text'],
- value: '@@ -45,10 +45,4 @@\n ort \n-before\n',
- },
- {
- type: 'setIfMissing',
- origin: 'remote',
- path: [{_key: 'b1'}, 'children'],
- value: [],
- },
- {
- type: 'insert',
- origin: 'remote',
- position: 'after',
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}],
- items: [
- {_type: 'span', _key: 's-before', marks: [], text: 'before'},
- ] as unknown as JSONValue[],
- },
- {
- type: 'set',
- origin: 'remote',
- path: [{_key: 'b1'}, 'children', {_key: 's-before'}, 'marks'],
- value: ['strong'],
- },
- ])
-
- // One microtask for the store commit to land; the transaction must
- // then have applied in full. Sampling any later would miss the flash,
- // because the whole-value repair heals it within a few hundred
- // milliseconds.
- await Promise.resolve()
-
- expect(editor.getSnapshot().context.value).toEqual([
- {
- _type: 'block',
- _key: 'b1',
- style: 'normal',
- markDefs: [],
- children: [
- {
- _type: 'span',
- _key: 'b1-span',
- text: 'ALPHA The newsroom shipped its quarterly report ',
- marks: [],
- },
- {
- _type: 'span',
- _key: 's-before',
- text: 'before',
- marks: ['strong'],
- },
- {_type: 'span', _key: 's-dawn', text: ' dawn.', marks: []},
- ],
- },
- ])
- // the transaction arrived over the patch channel; nothing pushed back
- expect(store.pushPatches).not.toHaveBeenCalled()
- expect(store.pushValue).not.toHaveBeenCalled()
- })
-
- test('Scenario: a remote text set applies to a specific span', async () => {
- const store = createMockPatchStore([
- makeBlock('b1', 'First'),
- makeBlock('b2', 'Second'),
- ])
- const {editor, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual(
- ['B: First', 'B: Second'].join('\n'),
- )
- })
-
- store.receiveRemotePatches([
- {
- type: 'set',
- origin: 'remote',
- path: [{_key: 'b2'}, 'children', {_key: 'b2-span'}, 'text'],
- value: 'Second, edited remotely',
- },
- ])
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual(
- ['B: First', 'B: Second, edited remotely'].join('\n'),
- )
- })
- })
-
- test('Scenario: remote patches apply during local typing without losing local changes', async () => {
- const store = createMockPatchStore([makeBlock('b1', 'Hello')])
- const {editor, locator, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: Hello')
- })
-
- await locator.click()
- editor.send({
- type: 'select',
- at: {
- anchor: {
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}],
- offset: 5,
- },
- focus: {
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}],
- offset: 5,
- },
- },
- })
- editor.send({type: 'insert.text', text: ' world'})
-
- // remote patches arrive while the local write is still unflushed
- store.receiveRemotePatches([
- {
- type: 'insert',
- origin: 'remote',
- position: 'after',
- path: [{_key: 'b1'}],
- items: [makeBlock('b2', 'From remote')] as unknown as JSONValue[],
- },
- ])
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual(
- ['B: Hello world|', 'B: From remote'].join('\n'),
- )
- })
- })
-
- test('Scenario: local edits push operational patches instead of whole values', async () => {
- const store = createMockPatchStore()
- const {editor, locator, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await locator.click()
- editor.send({type: 'insert.text', text: 'Hello'})
-
- await vi.waitFor(() => {
- expect(store.pushPatches).toHaveBeenCalled()
- })
-
- // the store converged on the editor value purely through patches
- await vi.waitFor(() => {
- expect(
- toTextspec({
- value: store.getValue(),
- schema: editor.getSnapshot().context.schema,
- selection: null,
- }),
- ).toEqual('B: Hello')
- })
- expect(store.pushValue).not.toHaveBeenCalled()
- })
-
- test('Scenario: the editor converges to the store value when remote patches cannot apply', async () => {
- const store = createMockPatchStore([makeBlock('b1', 'Hello')])
- const {editor, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: Hello')
- })
-
- // Another client, working from a diverged view of the document,
- // replaced a span this client doesn't have. Its keyed operations
- // don't resolve here (the editor logs and skips them), but the
- // store (server) accepted the transaction.
- store.receiveRemoteTransaction(
- [
- {
- ...makeBlock('b1', ''),
- children: [
- {_type: 'span', _key: 'other-1', text: 'Hello there', marks: []},
- ],
- },
- ],
- [
- {
- type: 'unset',
- origin: 'remote',
- path: [{_key: 'b1'}, 'children', {_key: 'nonexistent'}],
- },
- {
- type: 'insert',
- origin: 'remote',
- position: 'after',
- path: [{_key: 'b1'}, 'children', {_key: 'also-nonexistent'}],
- items: [
- {_type: 'span', _key: 'other-1', text: 'Hello there', marks: []},
- ] as unknown as JSONValue[],
- },
- ],
- )
-
- // The whole-value repair kicks in and converges the editor
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: Hello there')
- })
- })
-
- test('Scenario: concurrent same-range formatting converges to the store value', async () => {
- // Both clients format the same range at the same moment: while this
- // client's own patch push is still in flight, the other client's
- // transaction arrives. Its keyed operations were produced against a
- // different view of the document, so applying them here garbles the
- // editor; the repair sync must still converge the editor to the
- // store (server) truth, even though the value-change notification is
- // absorbed as the push acknowledgement.
- const store = createMockPatchStore([makeBlock('b1', 'Hello world')])
- const {editor, locator, unmount} = await createSyncedEditor({
- store,
- schemaDefinition: defineSchema({decorators: [{name: 'strong'}]}),
- })
- cleanup = unmount
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual('B: Hello world')
- })
-
- // The server truth after both transactions: the other client bolded
- // "Hello" (splitting the span its way) on top of our bolding of
- // "world"
- const mergedValue = [
- {
- ...makeBlock('b1', ''),
- children: [
- {_type: 'span', _key: 'r1', text: 'Hello', marks: ['strong']},
- {_type: 'span', _key: 'b1-span', text: ' ', marks: []},
- {_type: 'span', _key: 'l1', text: 'world', marks: ['strong']},
- ],
- },
- ]
-
- // When our push goes out, the concurrent remote transaction comes
- // back interleaved with it, before the machine settles
- store.pushPatches.mockImplementationOnce(() => {
- store.receiveRemoteTransaction(mergedValue, [
- {
- type: 'set',
- origin: 'remote',
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}, 'text'],
- value: ' world',
- },
- {
- type: 'insert',
- origin: 'remote',
- position: 'before',
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}],
- items: [
- {_type: 'span', _key: 'r1', text: 'Hello', marks: ['strong']},
- ] as unknown as JSONValue[],
- },
- ])
- })
-
- // Local client bolds "world" (splits b1-span into two spans)
- await locator.click()
- editor.send({
- type: 'select',
- at: {
- anchor: {
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}],
- offset: 6,
- },
- focus: {
- path: [{_key: 'b1'}, 'children', {_key: 'b1-span'}],
- offset: 11,
- },
- },
- })
- editor.send({type: 'decorator.add', decorator: 'strong'})
-
- await vi.waitFor(() => {
- expect(store.pushPatches).toHaveBeenCalled()
- })
-
- // Whatever the intermediate misapplications, the editor must end up
- // mirroring the store value
- await vi.waitFor(() => {
- expect(editor.getSnapshot().context.value).toEqual(store.getValue())
- })
- })
-
- test('Scenario: a remote patch applied while a local edit is pending is in the pushed value', async () => {
- const keyGenerator = createTestKeyGenerator('stored-')
- const fooBlockKey = keyGenerator()
- const fooSpanKey = keyGenerator()
- const barBlockKey = keyGenerator()
- const barSpanKey = keyGenerator()
- const {pushPatches: _, ...store} = createMockPatchStore([
- makeBlock(fooBlockKey, 'foo', fooSpanKey),
- makeBlock(barBlockKey, 'bar', barSpanKey),
- ])
- const {editor, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- const fooSpanPath = [{_key: fooBlockKey}, 'children', {_key: fooSpanKey}]
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual(['B: foo', 'B: bar'].join('\n'))
- })
-
- editor.send({
- type: 'select',
- at: {
- anchor: {path: fooSpanPath, offset: 3},
- focus: {path: fooSpanPath, offset: 3},
- },
- })
-
- await vi.waitFor(() => {
- expect(getEditorText(editor)).toEqual(['B: foo|', 'B: bar'].join('\n'))
- })
-
- editor.send({type: 'insert.text', text: 'baz'})
- store.receiveRemotePatches([
- {
- type: 'diffMatchPatch',
- origin: 'remote',
- path: [{_key: barBlockKey}, 'children', {_key: barSpanKey}, 'text'],
- value: '@@ -1,3 +1,6 @@\n bar\n+baz\n',
- },
- ])
-
- await vi.waitFor(() => {
- expect(store.pushValue.mock.calls).toEqual([
- [
- [
- makeBlock(fooBlockKey, 'foobaz', fooSpanKey),
- makeBlock(barBlockKey, 'barbaz', barSpanKey),
- ],
- ],
- ])
- })
- })
-
- test('Scenario: a throwing `pushPatches` falls back to a whole-value push', async () => {
- const store = createMockPatchStore()
- store.pushPatches.mockImplementation(() => {
- throw new Error('cannot convert')
- })
- const {editor, locator, unmount} = await createSyncedEditor({store})
- cleanup = unmount
-
- await locator.click()
- editor.send({type: 'insert.text', text: 'Hello'})
-
- await vi.waitFor(() => {
- expect(store.pushValue).toHaveBeenCalled()
- })
-
- const pushedValue = store.pushValue.mock.lastCall?.[0] ?? []
- expect(
- toTextspec({
- value: pushedValue,
- schema: editor.getSnapshot().context.schema,
- selection: null,
- }),
- ).toEqual('B: Hello')
- })
- })
-})
diff --git a/packages/plugin-sdk-value/src/presence-caret.test.ts b/packages/plugin-sdk-value/src/presence-caret.test.ts
deleted file mode 100644
index 229a9709e9..0000000000
--- a/packages/plugin-sdk-value/src/presence-caret.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import {describe, expect, it} from 'vitest'
-import {getCaretColor} from './presence-caret'
-
-describe(getCaretColor.name, () => {
- it('gives the same user the same colour every time', () => {
- expect(getCaretColor('user-abc')).toBe(getCaretColor('user-abc'))
- })
-
- it('always returns a colour, whatever the id looks like', () => {
- for (const id of [
- '',
- 'a',
- 'user-abc',
- 'p8xDvUMxC',
- '你好',
- '0'.repeat(500),
- ]) {
- expect(getCaretColor(id)).toMatch(/^#[0-9a-f]{6}$/)
- }
- })
-
- it('spreads a realistic set of users across several colours', () => {
- const ids = Array.from({length: 12}, (_, index) => `user-${index}`)
-
- const colors = new Set(ids.map(getCaretColor))
-
- // Not one colour for everyone, which is what a broken hash would give.
- expect(colors.size).toBeGreaterThan(2)
- })
-
- it('does not collapse ids that differ only by order', () => {
- // A sum-of-characters hash would give these the same colour.
- expect(getCaretColor('ab')).not.toBe(getCaretColor('ba'))
- })
-})
diff --git a/packages/plugin-sdk-value/src/presence-caret.tsx b/packages/plugin-sdk-value/src/presence-caret.tsx
deleted file mode 100644
index 7a75f9f0c0..0000000000
--- a/packages/plugin-sdk-value/src/presence-caret.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import type {PropsWithChildren} from 'react'
-import type {RenderCursorFunction, SDKRemoteCursor} from './plugin.sdk-presence'
-
-/**
- * Mid-tone hues, so a caret stays legible whether the app is light or dark. This
- * package cannot read the app's theme, so it does not try.
- */
-const CARET_COLORS = [
- '#e0508a',
- '#c05fd8',
- '#7c66e8',
- '#2f8fdd',
- '#1f9c8f',
- '#4f9c2f',
- '#c98a1c',
- '#d4603a',
-]
-
-const DOT_SIZE = 6
-
-/**
- * Picks a stable colour for a participant.
- *
- * Keyed on the user rather than the session, so one person in two tabs draws two
- * carets in the same colour. The Studio colours by user for the same reason.
- *
- * @public
- */
-export function getCaretColor(userId: string): string {
- let hash = 0
- for (let index = 0; index < userId.length; index++) {
- hash = (hash * 31 + userId.charCodeAt(index)) % 1000003
- }
- return CARET_COLORS[hash % CARET_COLORS.length]
-}
-
-/**
- * Draws a remote caret when no `renderCursor` was given: a coloured line with a
- * dot above it, and the participant's name on hover.
- *
- * Deliberately plain, and styled inline so it needs no stylesheet. Pass your own
- * `renderCursor` to match your design.
- *
- * @public
- */
-export const renderDefaultCursor: RenderCursorFunction =
- (cursor) => (props) => (
- {props.children}
- )
-
-function DefaultCaret(props: PropsWithChildren<{cursor: SDKRemoteCursor}>) {
- const {cursor, children} = props
- const color = getCaretColor(cursor.user.sanityUserId)
- const displayName = cursor.user.profile.displayName
-
- return (
- <>
-
-
-
- {children}
- >
- )
-}
diff --git a/packages/plugin-sdk-value/src/presence-cursors.test.ts b/packages/plugin-sdk-value/src/presence-cursors.test.ts
deleted file mode 100644
index dc2830e7f4..0000000000
--- a/packages/plugin-sdk-value/src/presence-cursors.test.ts
+++ /dev/null
@@ -1,235 +0,0 @@
-import type {EditorSelection} from '@portabletext/editor'
-import {createElement, type PropsWithChildren, type ReactElement} from 'react'
-import {describe, expect, it, vi} from 'vitest'
-import {
- collapseToCaret,
- recordCursorMove,
- resolveCursorSelection,
- toRangeDecorations,
- type CursorOverride,
- type RemoteCursor,
-} from './presence-cursors'
-
-function span(
- anchorOffset: number,
- focusOffset: number,
- key = 'span-1',
-): NonNullable {
- const path = [{_key: 'block-1'}, 'children', {_key: key}]
- return {
- anchor: {path, offset: anchorOffset},
- focus: {path, offset: focusOffset},
- }
-}
-
-function renderCursor(): (props: PropsWithChildren) => ReactElement {
- return (props) => createElement('span', null, props.children)
-}
-
-function overridesOf(
- ...entries: Array<[string, CursorOverride]>
-): ReadonlyMap {
- return new Map(entries)
-}
-
-describe(collapseToCaret.name, () => {
- it('leaves an absent selection absent', () => {
- expect(collapseToCaret(null)).toBeNull()
- })
-
- it('puts both points at the focus, so no text reads as selected', () => {
- expect(collapseToCaret(span(2, 7))).toEqual({
- anchor: span(2, 7).focus,
- focus: span(2, 7).focus,
- })
- })
-
- it('leaves an already collapsed selection where it is', () => {
- expect(collapseToCaret(span(4, 4))).toEqual(span(4, 4))
- })
-})
-
-describe(resolveCursorSelection.name, () => {
- it('collapses a fresh report when nothing has moved it', () => {
- const cursor: RemoteCursor = {sessionId: 'a', selection: span(2, 6)}
-
- expect(resolveCursorSelection(cursor, undefined)).toEqual(
- collapseToCaret(span(2, 6)),
- )
- })
-
- it('keeps a locally moved caret while the participant reports the same selection', () => {
- const cursor: RemoteCursor = {sessionId: 'a', selection: span(1, 1)}
- // A fresh object with identical values, which is what every heartbeat sends.
- const override: CursorOverride = {reported: span(1, 1), current: span(9, 9)}
-
- expect(resolveCursorSelection(cursor, override)).toEqual(span(9, 9))
- })
-
- it('drops a locally moved caret once the participant actually moves', () => {
- const cursor: RemoteCursor = {sessionId: 'a', selection: span(3, 3)}
- const override: CursorOverride = {reported: span(1, 1), current: span(9, 9)}
-
- expect(resolveCursorSelection(cursor, override)).toEqual(span(3, 3))
- })
-
- it('treats a move to a different span as a move, comparing keys not identity', () => {
- // Paths carry `{_key}` objects, so a value comparison is what makes a report
- // from a different span read as a move rather than as the same position.
- const override: CursorOverride = {
- reported: span(1, 1, 'span-1'),
- current: span(9, 9),
- }
- const cursor: RemoteCursor = {
- sessionId: 'a',
- selection: span(1, 1, 'span-2'),
- }
-
- expect(resolveCursorSelection(cursor, override)).toEqual(
- span(1, 1, 'span-2'),
- )
- })
-
- it('has nothing to draw for a participant who cleared their selection', () => {
- expect(
- resolveCursorSelection({sessionId: 'a', selection: null}, undefined),
- ).toBeNull()
- })
-})
-
-describe(recordCursorMove.name, () => {
- const cursor: RemoteCursor = {sessionId: 'a', selection: span(1, 1)}
- const cursors = [cursor]
-
- it('records the move against the selection it moved from', () => {
- const next = recordCursorMove(new Map(), cursors, cursor, span(5, 5))
-
- expect(next.get('a')).toEqual({reported: span(1, 1), current: span(5, 5)})
- })
-
- it('collapses a range the editor reports', () => {
- const next = recordCursorMove(new Map(), cursors, cursor, span(5, 9))
-
- expect(next.get('a')?.current).toEqual(collapseToCaret(span(5, 9)))
- })
-
- it('returns the same map when the caret did not actually move', () => {
- const overrides = overridesOf([
- 'a',
- {reported: span(1, 1), current: span(5, 5)},
- ])
-
- expect(recordCursorMove(overrides, cursors, cursor, span(5, 5))).toBe(
- overrides,
- )
- })
-
- it('re-records when the participant has reported a new selection since', () => {
- const overrides = overridesOf([
- 'a',
- {reported: span(1, 1), current: span(5, 5)},
- ])
- const moved: RemoteCursor = {sessionId: 'a', selection: span(3, 3)}
-
- const next = recordCursorMove(overrides, [moved], moved, span(5, 5))
-
- expect(next.get('a')).toEqual({reported: span(3, 3), current: span(5, 5)})
- })
-
- it('forgets participants who have left, so overrides stay bounded', () => {
- const overrides = overridesOf(
- ['a', {reported: span(1, 1), current: span(5, 5)}],
- ['gone', {reported: span(2, 2), current: span(7, 7)}],
- )
-
- const next = recordCursorMove(overrides, cursors, cursor, span(6, 6))
-
- expect([...next.keys()]).toEqual(['a'])
- })
-})
-
-describe(toRangeDecorations.name, () => {
- const cursors: RemoteCursor[] = [
- {sessionId: 'a', selection: span(1, 1)},
- {sessionId: 'b', selection: span(2, 2)},
- ]
-
- it('draws one decoration per participant, tagged with the session', () => {
- const decorations = toRangeDecorations({
- cursors,
- overrides: new Map(),
- renderCursor,
- })
-
- expect(decorations).toHaveLength(2)
- expect(decorations.map((decoration) => decoration.payload)).toEqual([
- {sessionId: 'a'},
- {sessionId: 'b'},
- ])
- expect(decorations[0].selection).toEqual(span(1, 1))
- })
-
- it('draws a moved caret where it was moved to', () => {
- const overrides = overridesOf([
- 'a',
- {reported: span(1, 1), current: span(9, 9)},
- ])
-
- const [decoration] = toRangeDecorations({
- cursors,
- overrides,
- renderCursor,
- })
-
- expect(decoration.selection).toEqual(span(9, 9))
- })
-
- it('skips a participant with no caret to draw', () => {
- const decorations = toRangeDecorations({
- cursors: [{sessionId: 'a', selection: null}, cursors[1]],
- overrides: new Map(),
- renderCursor,
- })
-
- expect(decorations.map((decoration) => decoration.payload)).toEqual([
- {sessionId: 'b'},
- ])
- })
-
- it('reports moves against the right participant', () => {
- const onCursorMoved = vi.fn()
-
- const decorations = toRangeDecorations({
- cursors,
- overrides: new Map(),
- renderCursor,
- onCursorMoved,
- })
- decorations[1].onMoved?.({
- rangeDecoration: decorations[1],
- newSelection: span(4, 4),
- origin: 'local',
- })
-
- expect(onCursorMoved).toHaveBeenCalledWith(cursors[1], span(4, 4))
- })
-
- it('leaves onMoved unset when the caller does not want moves', () => {
- const [decoration] = toRangeDecorations({
- cursors: [cursors[0]],
- overrides: new Map(),
- renderCursor,
- })
-
- expect(decoration.onMoved).toBeUndefined()
- })
-
- it('takes the component from renderCursor, once per participant', () => {
- const render = vi.fn(renderCursor)
-
- toRangeDecorations({cursors, overrides: new Map(), renderCursor: render})
-
- expect(render).toHaveBeenCalledTimes(2)
- expect(render).toHaveBeenCalledWith(cursors[0])
- })
-})
diff --git a/packages/plugin-sdk-value/src/presence-cursors.ts b/packages/plugin-sdk-value/src/presence-cursors.ts
deleted file mode 100644
index 8a49803336..0000000000
--- a/packages/plugin-sdk-value/src/presence-cursors.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-import type {EditorSelection, RangeDecoration} from '@portabletext/editor'
-import {isEqualSelections} from '@portabletext/editor/utils'
-import type {PropsWithChildren, ReactElement} from 'react'
-
-/**
- * A remote participant's position in the editor.
- *
- * @public
- */
-export interface RemoteCursor {
- /**
- * Identifies one editing session rather than one person. The same user in two
- * tabs reports two sessions and therefore draws two carets.
- */
- sessionId: string
- /**
- * The selection the participant last reported, or `null` when they have none.
- */
- selection: EditorSelection
-}
-
-/**
- * Where the local editor has pushed a remote caret, and the reported selection
- * it was pushed from.
- *
- * Typing above or inside a remote caret moves it, and the editor reports the
- * new position through `onMoved`. Keeping the selection it moved from is what
- * lets a later report from that participant take over again.
- *
- * @public
- */
-export interface CursorOverride {
- reported: EditorSelection
- current: EditorSelection
-}
-
-/**
- * Options for {@link toRangeDecorations}.
- *
- * @public
- */
-export interface RangeDecorationOptions {
- cursors: readonly TCursor[]
- overrides: ReadonlyMap
- /**
- * Builds the component that draws one caret. The plugin has no opinion about
- * how a caret looks, so this is the caller's to provide.
- */
- renderCursor: (cursor: TCursor) => (props: PropsWithChildren) => ReactElement
- onCursorMoved?: (cursor: TCursor, selection: EditorSelection) => void
-}
-
-/**
- * Reduces a selection to a caret at its focus point.
- *
- * Presence answers where someone is, so decorating their whole selection would
- * highlight text the local user never selected. The Studio collapses the same
- * way, which keeps the two consistent when both are open on a document.
- *
- * @public
- */
-export function collapseToCaret(selection: EditorSelection): EditorSelection {
- if (selection === null) {
- return null
- }
- return {anchor: selection.focus, focus: selection.focus}
-}
-
-/**
- * Where one remote caret should be drawn.
- *
- * A caret the local editor has moved keeps that moved position for as long as
- * the participant keeps reporting the same selection. A changed report wins,
- * because the participant has actually moved.
- *
- * @public
- */
-export function resolveCursorSelection(
- cursor: RemoteCursor,
- override: CursorOverride | undefined,
-): EditorSelection {
- if (override && isEqualSelections(override.reported, cursor.selection)) {
- return override.current
- }
- return collapseToCaret(cursor.selection)
-}
-
-/**
- * Records where the editor moved a caret to.
- *
- * Overrides for sessions that are no longer present are dropped, so a long
- * editing session does not accumulate one entry per participant who ever
- * visited. Returns the map untouched when nothing changed.
- *
- * @public
- */
-export function recordCursorMove(
- overrides: ReadonlyMap,
- cursors: readonly RemoteCursor[],
- cursor: RemoteCursor,
- selection: EditorSelection,
-): ReadonlyMap {
- const moved = collapseToCaret(selection)
- const existing = overrides.get(cursor.sessionId)
- const alreadyRecorded =
- existing !== undefined &&
- isEqualSelections(existing.reported, cursor.selection) &&
- isEqualSelections(existing.current, moved)
-
- const live = new Set(cursors.map((candidate) => candidate.sessionId))
- const staleKeys = [...overrides.keys()].filter((key) => !live.has(key))
-
- if (alreadyRecorded && staleKeys.length === 0) {
- return overrides
- }
-
- const next = new Map(overrides)
- for (const key of staleKeys) {
- next.delete(key)
- }
- next.set(cursor.sessionId, {reported: cursor.selection, current: moved})
- return next
-}
-
-/**
- * Maps remote cursors to range decorations for
- * ``.
- *
- * Participants with no caret to draw are skipped, so someone who clears their
- * selection stops drawing without being treated as having left.
- *
- * @public
- */
-export function toRangeDecorations(
- options: RangeDecorationOptions,
-): RangeDecoration[] {
- const {cursors, overrides, renderCursor, onCursorMoved} = options
- const decorations: RangeDecoration[] = []
-
- for (const cursor of cursors) {
- const selection = resolveCursorSelection(
- cursor,
- overrides.get(cursor.sessionId),
- )
- if (selection === null) {
- continue
- }
- decorations.push({
- component: renderCursor(cursor),
- selection,
- payload: {sessionId: cursor.sessionId},
- onMoved: onCursorMoved
- ? (details) => onCursorMoved(cursor, details.newSelection)
- : undefined,
- })
- }
-
- return decorations
-}
diff --git a/packages/plugin-sdk-value/src/sdk-document-handle.ts b/packages/plugin-sdk-value/src/sdk-document-handle.ts
deleted file mode 100644
index 70715ddcf5..0000000000
--- a/packages/plugin-sdk-value/src/sdk-document-handle.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type {DocumentHandle, DocumentResource} from '@sanity/sdk-react'
-
-type DocumentHandleWithLegacySource = DocumentHandle & {
- source?: DocumentResource
-}
-
-export function normalizeDocumentHandle(
- handle: T & DocumentHandleWithLegacySource,
-): Omit {
- const {source, ...normalizedHandle} = handle
-
- if (normalizedHandle.resource !== undefined || source === undefined) {
- return normalizedHandle
- }
-
- return {...normalizedHandle, resource: source}
-}
diff --git a/packages/plugin-sdk-value/src/sdk-editable.test.ts b/packages/plugin-sdk-value/src/sdk-editable.test.ts
deleted file mode 100644
index 3b37004e26..0000000000
--- a/packages/plugin-sdk-value/src/sdk-editable.test.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import type {RangeDecoration} from '@portabletext/editor'
-import type {DocumentHandle} from '@sanity/sdk-react'
-import {describe, expect, it} from 'vitest'
-import type {RenderCursorFunction} from './plugin.sdk-presence'
-import {renderDefaultCursor} from './presence-caret'
-import {
- mergePresenceDecorations,
- resolveCursorRenderer,
- splitEditableProps,
- type SDKPortableTextEditableProps,
-} from './sdk-editable'
-
-function decoration(testId: string): RangeDecoration {
- return {
- component: (props) => props.children as never,
- selection: null,
- payload: {testId},
- }
-}
-
-describe(splitEditableProps.name, () => {
- const props: SDKPortableTextEditableProps = {
- 'documentId': 'doc-1',
- 'documentType': 'post',
- 'path': 'content',
- // The full handle, since any of these reaching the DOM is a React warning
- // and a broken document reference.
- 'projectId': 'project-1',
- 'dataset': 'production',
- 'perspective': 'drafts',
- 'liveEdit': false,
- 'resourceName': 'resource-1',
- // Genuine editable props
- 'style': {minHeight: 120},
- 'data-testid': 'editable',
- } as SDKPortableTextEditableProps
-
- it('keeps every handle field out of what reaches the editable', () => {
- // `satisfies` makes this list exhaustive: adding a field to `DocumentHandle`
- // breaks compilation here until it is also pulled out in the component, which
- // is what stops a new field being forwarded to the DOM as an attribute.
- const handleKeys = {
- dataset: true,
- documentId: true,
- documentType: true,
- liveEdit: true,
- perspective: true,
- projectId: true,
- resource: true,
- resourceName: true,
- } satisfies {[Key in keyof DocumentHandle]-?: true}
-
- // Every handle key has to be present in the input, or a field the component
- // forgets to pull out would be absent from the result for the wrong reason.
- const withEveryHandleField = {
- ...props,
- ...Object.fromEntries(Object.keys(handleKeys).map((key) => [key, 'set'])),
- path: 'content',
- } as SDKPortableTextEditableProps
-
- const {editableProps} = splitEditableProps(withEveryHandleField)
-
- for (const key of Object.keys(handleKeys)) {
- expect(editableProps).not.toHaveProperty(key)
- }
- })
-
- it('keeps its own props out of what reaches the editable', () => {
- const {editableProps} = splitEditableProps({
- ...props,
- renderCursor: () => (cursorProps) => cursorProps.children as never,
- rangeDecorations: [decoration('caller')],
- })
-
- expect(editableProps).not.toHaveProperty('path')
- expect(editableProps).not.toHaveProperty('renderCursor')
- expect(editableProps).not.toHaveProperty('rangeDecorations')
- })
-
- it('forwards everything else untouched', () => {
- const {editableProps} = splitEditableProps(props)
-
- expect(editableProps).toEqual({
- 'style': {minHeight: 120},
- 'data-testid': 'editable',
- })
- })
-
- it('collects the handle so the document is addressed correctly', () => {
- const {handle, path} = splitEditableProps(props)
-
- expect(path).toBe('content')
- expect(handle.documentId).toBe('doc-1')
- expect(handle.documentType).toBe('post')
- expect(handle.projectId).toBe('project-1')
- expect(handle.dataset).toBe('production')
- expect(handle.resourceName).toBe('resource-1')
- })
-
- it('maps the removed source alias to resource without forwarding it', () => {
- const source: SDKPortableTextEditableProps['source'] = {
- projectId: 'source-project',
- dataset: 'source-dataset',
- }
- const legacyProps = {
- 'documentId': 'doc-1',
- 'documentType': 'post',
- 'path': 'content',
- 'source': source,
- 'data-testid': 'editable',
- }
- const {handle, editableProps} = splitEditableProps(legacyProps)
-
- expect(handle).toEqual({
- documentId: 'doc-1',
- documentType: 'post',
- resource: {projectId: 'source-project', dataset: 'source-dataset'},
- })
- expect(editableProps).toEqual({'data-testid': 'editable'})
- })
-
- it('omits handle fields the caller never passed', () => {
- // The SDK resolves an ambient perspective from `ResourceProvider` with
- // `Object.hasOwn`, so a `perspective: undefined` key overrides the context
- // value instead of deferring to it. Same for the resource fields, which
- // decide the project and dataset.
- const {handle} = splitEditableProps({
- documentId: 'doc-1',
- documentType: 'post',
- path: 'content',
- } as SDKPortableTextEditableProps)
-
- expect(Object.keys(handle).sort()).toEqual(['documentId', 'documentType'])
- expect('perspective' in handle).toBe(false)
- })
-
- it('forwards an explicitly undefined perspective, matching a direct hook call', () => {
- // Passing `perspective={maybeUndefined}` here has to behave exactly as
- // passing it straight to the SDK hook does: the key is present, so it wins
- // over the context. A value check would let the wrapper drift from the
- // direct hook call without this test noticing.
- const {handle} = splitEditableProps({
- documentId: 'doc-1',
- documentType: 'post',
- path: 'content',
- perspective: undefined,
- } as SDKPortableTextEditableProps)
-
- expect('perspective' in handle).toBe(true)
- })
-
- it('carries the perspective through, which decides the document reported', () => {
- const {handle} = splitEditableProps({
- ...props,
- perspective: {releaseName: 'autumn'},
- })
-
- expect(handle.perspective).toEqual({releaseName: 'autumn'})
- })
-})
-
-describe(mergePresenceDecorations.name, () => {
- const caller = [decoration('caller')]
- const cursors = [decoration('cursor-a'), decoration('cursor-b')]
-
- it("appends carets after the caller's own decorations", () => {
- const merged = mergePresenceDecorations(caller, cursors, true)
-
- expect(merged?.map((item) => item.payload?.['testId'])).toEqual([
- 'caller',
- 'cursor-a',
- 'cursor-b',
- ])
- })
-
- it('does not drop the caller decorations, which replacing would', () => {
- const merged = mergePresenceDecorations(caller, cursors, true)
-
- expect(merged).toContain(caller[0])
- })
-
- it('returns just the carets when the caller passed none', () => {
- expect(mergePresenceDecorations(undefined, cursors, true)).toEqual(cursors)
- })
-
- it('leaves the caller decorations alone when no caret component was given', () => {
- expect(mergePresenceDecorations(caller, cursors, false)).toBe(caller)
- })
-
- it('stays undefined when there is nothing at all to draw', () => {
- expect(mergePresenceDecorations(undefined, cursors, false)).toBeUndefined()
- })
-})
-
-describe(resolveCursorRenderer.name, () => {
- const custom: RenderCursorFunction = () => (props) => props.children as never
-
- it('draws the built-in caret when the app gave none', () => {
- const resolved = resolveCursorRenderer(undefined)
-
- expect(resolved.renderCursor).toBe(renderDefaultCursor)
- expect(resolved.drawCursors).toBe(true)
- })
-
- it("uses the app's caret when it gave one", () => {
- const resolved = resolveCursorRenderer(custom)
-
- expect(resolved.renderCursor).toBe(custom)
- expect(resolved.drawCursors).toBe(true)
- })
-
- it('draws nothing when carets are switched off with null', () => {
- expect(resolveCursorRenderer(null).drawCursors).toBe(false)
- })
-})
diff --git a/packages/plugin-sdk-value/src/sdk-editable.tsx b/packages/plugin-sdk-value/src/sdk-editable.tsx
deleted file mode 100644
index 2929e5adeb..0000000000
--- a/packages/plugin-sdk-value/src/sdk-editable.tsx
+++ /dev/null
@@ -1,203 +0,0 @@
-import {
- PortableTextEditable,
- type PortableTextEditableProps,
- type RangeDecoration,
-} from '@portabletext/editor'
-import type {DocumentHandle, DocumentResource} from '@sanity/sdk-react'
-import {useMemo} from 'react'
-import {
- SDKPresencePlugin,
- useSDKPresenceCursors,
- type RenderCursorFunction,
-} from './plugin.sdk-presence'
-import {SDKValuePlugin} from './plugin.sdk-value'
-import {renderDefaultCursor} from './presence-caret'
-import {normalizeDocumentHandle} from './sdk-document-handle'
-
-/**
- * Props for {@link SDKPortableTextEditable}.
- *
- * @public
- */
-export interface SDKPortableTextEditableProps
- extends
- DocumentHandle,
- // `resource` is both a document handle field and an RDFa HTML attribute, so
- // the handle wins. Dropping the attribute costs nothing in an editor.
- Omit {
- /**
- * @deprecated Use `resource` instead.
- */
- source?: DocumentResource
- /**
- * The document path of the Portable Text field, for example `content`.
- */
- path: string
- /**
- * Draws one remote participant's caret. Omit it for the built-in caret, which
- * needs no styling of your own. Pass `null` to draw no carets at all while
- * still reporting the local user's presence.
- */
- renderCursor?: RenderCursorFunction | null
-}
-
-/**
- * What {@link splitEditableProps} pulls apart.
- *
- * @internal
- */
-export interface SplitEditableProps {
- handle: DocumentHandle
- path: string
- renderCursor: RenderCursorFunction | null | undefined
- rangeDecorations: RangeDecoration[] | undefined
- editableProps: Omit<
- PortableTextEditableProps,
- keyof DocumentHandle | 'rangeDecorations'
- >
-}
-
-/**
- * A `PortableTextEditable` wired to a Sanity document: the field's value syncs
- * both ways, the local user's caret is reported, and other people's carets are
- * drawn.
- *
- * Place it inside `EditorProvider` in place of `PortableTextEditable`. Every
- * other prop is forwarded untouched, and `rangeDecorations` you pass are kept
- * and merged with the presence carets rather than replaced.
- *
- * Nothing else is needed: this replaces a separate `SDKValuePlugin`.
- *
- * @example
- * ```tsx nocheck
- *
- * (props) => (
- * {props.children}
- * )}
- * />
- *
- * ```
- *
- * @public
- */
-export function SDKPortableTextEditable(props: SDKPortableTextEditableProps) {
- const {handle, path, renderCursor, rangeDecorations, editableProps} =
- splitEditableProps(props)
-
- const renderer = resolveCursorRenderer(renderCursor)
-
- const cursors = useSDKPresenceCursors({
- ...handle,
- path,
- renderCursor: renderer.renderCursor,
- })
-
- const decorations = useMemo(
- () =>
- mergePresenceDecorations(rangeDecorations, cursors, renderer.drawCursors),
- [cursors, rangeDecorations, renderer.drawCursors],
- )
-
- return (
- <>
-
-
-
- >
- )
-}
-
-/**
- * Splits the props into the document handle, this component's own props, and
- * what is forwarded to `PortableTextEditable`. Keeping handle fields out of the
- * forwarded set is what stops them reaching the DOM as attributes.
- *
- * @internal
- */
-export function splitEditableProps(
- props: SDKPortableTextEditableProps,
-): SplitEditableProps {
- const normalizedProps = normalizeDocumentHandle(props)
- const {
- documentId,
- documentType,
- projectId,
- dataset,
- resource,
- resourceName,
- liveEdit,
- perspective,
- path,
- renderCursor,
- rangeDecorations,
- ...editableProps
- } = normalizedProps
-
- return {
- // Only the fields the caller actually passed. The SDK resolves an ambient
- // perspective and resource from context with `Object.hasOwn`, so forwarding
- // `perspective: undefined` would override what `ResourceProvider` set rather
- // than defer to it, and the field would sync and report against the draft
- // instead of the release the app is showing.
- handle: {
- documentId,
- documentType,
- ...('projectId' in props && {projectId}),
- ...('dataset' in props && {dataset}),
- ...('resource' in normalizedProps && {resource}),
- ...('resourceName' in props && {resourceName}),
- ...('liveEdit' in props && {liveEdit}),
- ...('perspective' in props && {perspective}),
- },
- path,
- renderCursor,
- rangeDecorations,
- editableProps,
- }
-}
-
-/**
- * Decides which caret component to draw with, and whether to draw at all.
- *
- * Presence is subscribed to either way, because hooks cannot be called
- * conditionally, so switching carets off discards the decorations rather than
- * skipping the work.
- *
- * @internal
- */
-export function resolveCursorRenderer(
- renderCursor: RenderCursorFunction | null | undefined,
-): {renderCursor: RenderCursorFunction; drawCursors: boolean} {
- return {
- renderCursor: renderCursor ?? renderDefaultCursor,
- drawCursors: renderCursor !== null,
- }
-}
-
-/**
- * Appends the presence carets to whatever decorations the caller passed, so
- * theirs survive. The Studio merges the same way. When carets are switched off
- * the caller's own decorations pass straight through.
- *
- * @internal
- */
-export function mergePresenceDecorations(
- rangeDecorations: RangeDecoration[] | undefined,
- cursors: RangeDecoration[],
- drawCursors: boolean,
-): RangeDecoration[] | undefined {
- if (!drawCursors) {
- return rangeDecorations
- }
- return [...(rangeDecorations ?? []), ...cursors]
-}
-
-/**
- * Splitting the props by hand is what keeps document handle fields off the DOM,
- * so every field has to be listed above. `sdk-editable.test.ts` fails to compile
- * if `DocumentHandle` gains one. Note that `@sanity/sdk-react` adds fields to the
- * core handle, so it has to be read from there.
- */
diff --git a/packages/plugin-sdk-value/src/selection-compatibility.test.ts b/packages/plugin-sdk-value/src/selection-compatibility.test.ts
deleted file mode 100644
index d4d7884e0e..0000000000
--- a/packages/plugin-sdk-value/src/selection-compatibility.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import type {EditorSelection} from '@portabletext/editor'
-import type {UseReportPresenceOptions} from '@sanity/sdk-react'
-import {describe, expect, it} from 'vitest'
-
-/**
- * The SDK carries a Portable Text selection over the presence wire, and the
- * editor consumes the same shape as a range decoration. This plugin passes
- * values straight through in both directions rather than converting them, so
- * the two types have to stay structurally identical. The two functions below
- * are the whole conversion, and they stop compiling if either side drifts.
- */
-type ReportedSelection = UseReportPresenceOptions['selection']
-
-function asEditorSelection(
- reported: NonNullable,
-): EditorSelection {
- return reported
-}
-
-function asReportedSelection(selection: EditorSelection): ReportedSelection {
- return selection
-}
-
-describe('selection compatibility', () => {
- it('passes a reported selection to the editor unchanged', () => {
- const reported = {
- anchor: {
- path: [{_key: 'block-1'}, 'children', {_key: 'span-1'}],
- offset: 3,
- },
- focus: {
- path: [{_key: 'block-1'}, 'children', {_key: 'span-1'}],
- offset: 7,
- },
- backward: false,
- }
-
- expect(asEditorSelection(reported)).toBe(reported)
- })
-
- it('passes an editor selection to the wire unchanged, including an empty one', () => {
- expect(asReportedSelection(null)).toBeNull()
- })
-})
diff --git a/packages/plugin-sdk-value/src/test/apply-sanity-patch-operations.test.ts b/packages/plugin-sdk-value/src/test/apply-sanity-patch-operations.test.ts
deleted file mode 100644
index 890b69e944..0000000000
--- a/packages/plugin-sdk-value/src/test/apply-sanity-patch-operations.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import {makePatches, stringifyPatches} from '@sanity/diff-match-patch'
-import {describe, expect, test} from 'vitest'
-import {applyPatchOperations} from './apply-sanity-patch-operations'
-
-function dmp(before: string, after: string): string {
- return stringifyPatches(makePatches(before, after))
-}
-
-describe(applyPatchOperations.name, () => {
- test('sets by key path', () => {
- const doc = {
- content: [{_key: 'b1', children: [{_key: 's1', text: 'hello'}]}],
- }
- const result = applyPatchOperations(doc, {
- set: {'content[_key=="b1"].children[_key=="s1"].text': 'bye'},
- })
- expect(result).toEqual({
- content: [{_key: 'b1', children: [{_key: 's1', text: 'bye'}]}],
- })
- })
-
- // Content Lake never creates array items when setting: an unmatched keyed
- // or indexed segment is a silent no-op (verified against gradient's
- // jsonpath matcher, which only auto-creates missing object properties).
- // This applier used to mirror an @sanity/sdk bug that fabricated a
- // degenerate item instead; both are fixed to match the server.
- test('set with an unmatched key constraint is a no-op', () => {
- const doc = {content: [{_key: 'b1', text: 'hello'}]}
- const result = applyPatchOperations(doc, {
- set: {'content[_key=="b2"]': {_key: 'b2', text: 'bye'}},
- })
- expect(result).toEqual({content: [{_key: 'b1', text: 'hello'}]})
- })
-
- test('set on a property under an unmatched key constraint is a no-op', () => {
- const doc = {
- content: [
- {_key: 'b1', children: [{_key: 's1', text: 'hello', marks: []}]},
- ],
- }
- const result = applyPatchOperations(doc, {
- set: {'content[_key=="b1"].children[_key=="missing"].marks': ['m1']},
- })
- expect(result).toEqual(doc)
- })
-
- test('set still creates a missing property on an existing keyed item', () => {
- const doc = {content: [{_key: 'b1'}]}
- const result = applyPatchOperations(doc, {
- set: {'content[_key=="b1"].text': 'hello'},
- })
- expect(result).toEqual({content: [{_key: 'b1', text: 'hello'}]})
- })
-
- test('unset with an unresolvable path is a no-op', () => {
- const doc = {content: [{_key: 'b1', text: 'hello'}]}
- const result = applyPatchOperations(doc, {
- unset: ['content[_key=="nope"]'],
- })
- expect(result).toEqual(doc)
- })
-
- test('insert after a negative index appends', () => {
- const doc = {content: [{_key: 'a'}, {_key: 'b'}]}
- const result = applyPatchOperations(doc, {
- insert: {after: 'content[-1]', items: [{_key: 'c'}]},
- })
- expect(result).toEqual({content: [{_key: 'a'}, {_key: 'b'}, {_key: 'c'}]})
- })
-
- test('insert before a keyed sibling', () => {
- const doc = {content: [{_key: 'a'}, {_key: 'c'}]}
- const result = applyPatchOperations(doc, {
- insert: {before: 'content[_key=="c"]', items: [{_key: 'b'}]},
- })
- expect(result).toEqual({content: [{_key: 'a'}, {_key: 'b'}, {_key: 'c'}]})
- })
-
- test('unset by key', () => {
- const doc = {content: [{_key: 'a'}, {_key: 'b'}, {_key: 'c'}]}
- const result = applyPatchOperations(doc, {
- unset: ['content[_key=="b"]'],
- })
- expect(result).toEqual({content: [{_key: 'a'}, {_key: 'c'}]})
- })
-
- test('diffMatchPatch merges concurrent inserts into the same string', () => {
- // the fuzzy dmp application is why two clients typing into the same
- // span can both survive at the server
- const base = 'The quick brown fox'
- const doc = {text: base}
- const afterA = applyPatchOperations(doc, {
- diffMatchPatch: {text: dmp(base, 'The {A}0quick brown fox')},
- }) as {text: string}
- expect(afterA.text).toBe('The {A}0quick brown fox')
-
- const afterB = applyPatchOperations(afterA, {
- diffMatchPatch: {text: dmp(base, 'The quick brown fox {B}0')},
- }) as {text: string}
- expect(afterB.text).toBe('The {A}0quick brown fox {B}0')
- })
-
- test('diffMatchPatch against a non-string throws (transaction rejected)', () => {
- const doc = {text: 42}
- expect(() =>
- applyPatchOperations(doc, {
- diffMatchPatch: {text: dmp('abc', 'abd')},
- }),
- ).toThrow()
- })
-
- test('operations within one patch apply in content-lake order', () => {
- // set runs before insert regardless of key order in the record
- const doc = {content: [{_key: 'a', n: 1}]}
- const result = applyPatchOperations(doc, {
- insert: {after: 'content[-1]', items: [{_key: 'b'}]},
- set: {'content[_key=="a"].n': 2},
- })
- expect(result).toEqual({content: [{_key: 'a', n: 2}, {_key: 'b'}]})
- })
-})
diff --git a/packages/plugin-sdk-value/src/test/apply-sanity-patch-operations.ts b/packages/plugin-sdk-value/src/test/apply-sanity-patch-operations.ts
deleted file mode 100644
index 21007d6b88..0000000000
--- a/packages/plugin-sdk-value/src/test/apply-sanity-patch-operations.ts
+++ /dev/null
@@ -1,595 +0,0 @@
-import {applyPatches, parsePatch} from '@sanity/diff-match-patch'
-import {
- getIndexForKey,
- jsonMatch,
- slicePath,
- stringifyPath,
- type SingleValuePath,
-} from '@sanity/json-match'
-
-/**
- * Test-only port of the patch-operation applier in `@sanity/sdk`
- * (`packages/core/src/document/patchOperations.ts`), which itself mirrors
- * Content Lake behavior. The two-client browser tests use it so the mock
- * server applies transactions with real server semantics (json-match path
- * resolution, unresolvable paths as no-ops, fixed operation order) instead
- * of a forgiving best-effort applier.
- */
-
-/**
- * One Sanity patch as produced by `convertPatchesToSanity` or
- * `@sanity/diff-patch`'s `diffValue`.
- */
-export type SanityPatchOperationRecord = {
- set?: {[path: string]: unknown}
- setIfMissing?: {[path: string]: unknown}
- unset?: string[]
- inc?: {[path: string]: number}
- dec?: {[path: string]: number}
- insert?: {
- before?: string
- after?: string
- replace?: string
- items: unknown[]
- }
- diffMatchPatch?: {[path: string]: string}
-}
-
-type KeyedSegment = {_key: string}
-
-function isKeySegment(segment: unknown): segment is KeyedSegment {
- return (
- typeof segment === 'object' &&
- segment !== null &&
- '_key' in segment &&
- typeof (segment as KeyedSegment)._key === 'string'
- )
-}
-
-function isKeyedObject(item: unknown): item is KeyedSegment {
- return (
- typeof item === 'object' &&
- item !== null &&
- typeof (item as {_key?: unknown})._key === 'string'
- )
-}
-
-function generateArrayKey(length = 12): string {
- const numBytes = Math.ceil(length / 2)
- const bytes = crypto.getRandomValues(new Uint8Array(numBytes))
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0'))
- .join('')
- .slice(0, length)
-}
-
-function ensureArrayKeysDeep(input: R): R {
- if (!input || typeof input !== 'object') {
- return input
- }
-
- if (Array.isArray(input)) {
- if (!input.length) {
- return input
- }
- const first = input[0]
- if (typeof first !== 'object') {
- return input
- }
- if (input.every(isKeyedObject)) {
- return input
- }
- return input.map((item: unknown) => {
- if (!item || typeof item !== 'object') {
- return item
- }
- if (isKeyedObject(item)) {
- return ensureArrayKeysDeep(item)
- }
- const next = ensureArrayKeysDeep(item)
- return {...next, _key: generateArrayKey()}
- }) as R
- }
-
- return Object.fromEntries(
- Object.entries(input).map(([key, value]) => [
- key,
- ensureArrayKeysDeep(value),
- ]),
- ) as R
-}
-
-function setDeep(
- input: unknown,
- path: SingleValuePath,
- value: unknown,
-): unknown {
- const [currentSegment, ...restOfPath] = path
- if (currentSegment === undefined) {
- return value
- }
-
- if (typeof input !== 'object' || input === null) {
- if (typeof currentSegment === 'string') {
- return {[currentSegment]: setDeep(null, restOfPath, value)}
- }
-
- let index: number | undefined
- if (isKeySegment(currentSegment)) {
- index = 0
- } else if (typeof currentSegment === 'number' && currentSegment >= 0) {
- index = currentSegment
- } else {
- return input
- }
-
- return [
- ...Array.from({length: index}).fill(null),
- setDeep(null, restOfPath, value),
- ]
- }
-
- if (Array.isArray(input)) {
- let index: number | undefined
- if (isKeySegment(currentSegment)) {
- index = getIndexForKey(input, currentSegment._key) ?? input.length
- } else if (typeof currentSegment === 'number') {
- index =
- currentSegment < 0 ? input.length + currentSegment : currentSegment
- }
- if (index === undefined) {
- return input
- }
-
- if (index in input) {
- return input.map((nestedInput, i) =>
- i === index ? setDeep(nestedInput, restOfPath, value) : nestedInput,
- )
- }
-
- return [
- ...input,
- ...Array.from({length: index - input.length}).fill(null),
- setDeep(null, restOfPath, value),
- ]
- }
-
- if (typeof currentSegment === 'object') {
- return input
- }
-
- if (currentSegment in input) {
- return Object.fromEntries(
- Object.entries(input).map(([key, nestedInput]) =>
- key === currentSegment
- ? [key, setDeep(nestedInput, restOfPath, value)]
- : [key, nestedInput],
- ),
- )
- }
-
- return {...input, [currentSegment]: setDeep(null, restOfPath, value)}
-}
-
-function unsetDeep(input: unknown, path: SingleValuePath): unknown {
- const [currentSegment, ...restOfPath] = path
- if (currentSegment === undefined) {
- return input
- }
- if (typeof input !== 'object' || input === null) {
- return input
- }
-
- let resolved: string | number | undefined
- if (isKeySegment(currentSegment)) {
- resolved = getIndexForKey(input, currentSegment._key)
- } else if (
- typeof currentSegment === 'string' ||
- typeof currentSegment === 'number'
- ) {
- resolved = currentSegment
- }
- if (resolved === undefined) {
- return input
- }
-
- let segment: string | number = resolved
- if (typeof segment === 'number' && Array.isArray(input)) {
- segment = segment < 0 ? input.length + segment : segment
- }
- if (!(segment in input)) {
- return input
- }
-
- if (!restOfPath.length) {
- if (Array.isArray(input)) {
- return input.filter((_nestedInput, index) => index !== segment)
- }
- return Object.fromEntries(
- Object.entries(input).filter(([key]) => key !== segment.toString()),
- )
- }
-
- if (Array.isArray(input)) {
- return input.map((nestedInput, index) =>
- index === segment ? unsetDeep(nestedInput, restOfPath) : nestedInput,
- )
- }
-
- return Object.fromEntries(
- Object.entries(input).map(([key, value]) =>
- key === segment ? [key, unsetDeep(value, restOfPath)] : [key, value],
- ),
- )
-}
-
-/**
- * Whether every array-addressing segment (keyed or numeric) in the path
- * resolves to an existing array item. Content Lake auto-creates missing
- * object properties when setting, but never creates array items: a `set`
- * through an unresolvable keyed or indexed segment is a silent no-op
- * server-side (gradient's jsonpath matcher only auto-creates map
- * properties).
- */
-function resolvesArraySegments(input: unknown, path: SingleValuePath): boolean {
- let current: unknown = input
- for (const segment of path) {
- if (typeof segment === 'string') {
- current =
- typeof current === 'object' &&
- current !== null &&
- !Array.isArray(current)
- ? (current as {[key: string]: unknown})[segment]
- : undefined
- continue
- }
- if (!Array.isArray(current)) {
- return false
- }
- if (isKeySegment(segment)) {
- const index = getIndexForKey(current, segment._key)
- if (index === undefined) {
- return false
- }
- current = current[index]
- } else {
- const index = segment < 0 ? current.length + segment : segment
- if (!(index in current)) {
- return false
- }
- current = current[index]
- }
- }
- return true
-}
-
-function set(input: unknown, pathExpressionValues: {[path: string]: unknown}) {
- const result = Object.entries(pathExpressionValues)
- .flatMap(([pathExpression, replacementValue]) =>
- Array.from(jsonMatch(input, pathExpression)).map((matchEntry) => ({
- ...matchEntry,
- replacementValue,
- })),
- )
- .filter(({path}) => resolvesArraySegments(input, path))
- .reduce(
- (acc, {path, replacementValue}) => setDeep(acc, path, replacementValue),
- input,
- )
-
- return ensureArrayKeysDeep(result)
-}
-
-function setIfMissing(
- input: unknown,
- pathExpressionValues: {[path: string]: unknown},
-) {
- const result = Object.entries(pathExpressionValues)
- .flatMap(([pathExpression, replacementValue]) =>
- Array.from(jsonMatch(input, pathExpression)).map((matchEntry) => ({
- ...matchEntry,
- replacementValue,
- })),
- )
- .filter(
- (matchEntry) =>
- matchEntry.value === null || matchEntry.value === undefined,
- )
- .filter(({path}) => resolvesArraySegments(input, path))
- .reduce(
- (acc, {path, replacementValue}) => setDeep(acc, path, replacementValue),
- input,
- )
-
- return ensureArrayKeysDeep(result)
-}
-
-function unset(input: unknown, pathExpressions: string[]) {
- const result = pathExpressions
- .flatMap((pathExpression) => Array.from(jsonMatch(input, pathExpression)))
- // remove in reverse match order so array indexes stay valid while
- // unsetting
- .reverse()
- .reduce((acc, {path}) => unsetDeep(acc, path), input)
-
- return ensureArrayKeysDeep(result)
-}
-
-function inc(input: unknown, pathExpressionValues: {[path: string]: number}) {
- const result = Object.entries(pathExpressionValues)
- .flatMap(([pathExpression, valueToAdd]) =>
- Array.from(jsonMatch(input, pathExpression)).map((matchEntry) => ({
- ...matchEntry,
- valueToAdd,
- })),
- )
- .filter(
- (
- matchEntry: T,
- ): matchEntry is T & {value: number} =>
- typeof matchEntry.value === 'number',
- )
- .reduce(
- (acc, {path, value, valueToAdd}) =>
- setDeep(acc, path, value + valueToAdd),
- input,
- )
-
- return ensureArrayKeysDeep(result)
-}
-
-function dec(input: unknown, pathExpressionValues: {[path: string]: number}) {
- return inc(
- input,
- Object.fromEntries(
- Object.entries(pathExpressionValues)
- .filter(([, value]) => typeof value === 'number')
- .map(([key, value]) => [key, -value]),
- ),
- )
-}
-
-function insert(
- input: unknown,
- insertPatch: NonNullable,
-) {
- const {items, ...positions} = insertPatch
-
- let operation: 'before' | 'after' | 'replace' | undefined
- let pathExpression: string | undefined
-
- if (typeof positions.before === 'string') {
- operation = 'before'
- pathExpression = positions.before
- } else if (typeof positions.after === 'string') {
- operation = 'after'
- pathExpression = positions.after
- } else if (typeof positions.replace === 'string') {
- operation = 'replace'
- pathExpression = positions.replace
- }
- if (!operation || !pathExpression || !pathExpression.length) {
- return input
- }
-
- const arrayPath = slicePath(pathExpression, 0, -1)
- const positionPath = slicePath(pathExpression, -1)
-
- let result = input
-
- for (const {path, value} of jsonMatch(input, arrayPath)) {
- if (!Array.isArray(value)) {
- continue
- }
- let arr = value
-
- switch (operation) {
- case 'replace': {
- const indexesToRemove = new Set()
- let position = Infinity
-
- for (const itemMatch of jsonMatch(arr, positionPath)) {
- if (itemMatch.path.length !== 1) {
- continue
- }
- const [segment] = itemMatch.path
- if (typeof segment === 'string') {
- continue
- }
-
- let index: number | undefined
- if (typeof segment === 'number') {
- index = segment
- }
- if (typeof index === 'number' && index < 0) {
- index = arr.length + index
- }
- if (isKeySegment(segment)) {
- index = getIndexForKey(arr, segment._key)
- }
- if (typeof index !== 'number') {
- continue
- }
- if (index < 0) {
- index = arr.length + index
- }
-
- indexesToRemove.add(index)
- if (index < position) {
- position = index
- }
- }
-
- if (position === Infinity) {
- continue
- }
-
- arr = arr
- .map((item, index) => ({item, index}))
- .filter(({index}) => !indexesToRemove.has(index))
- .map(({item}) => item)
-
- arr = [
- ...arr.slice(0, position),
- ...items,
- ...arr.slice(position, arr.length),
- ]
-
- break
- }
- case 'before': {
- let position = Infinity
-
- for (const itemMatch of jsonMatch(arr, positionPath)) {
- if (itemMatch.path.length !== 1) {
- continue
- }
- const [segment] = itemMatch.path
- if (typeof segment === 'string') {
- continue
- }
-
- let index: number | undefined
- if (typeof segment === 'number') {
- index = segment
- }
- if (typeof index === 'number' && index < 0) {
- index = arr.length + index
- }
- if (isKeySegment(segment)) {
- index = getIndexForKey(arr, segment._key)
- }
- if (typeof index !== 'number') {
- continue
- }
- if (index < 0) {
- index = arr.length - index
- }
- if (index < position) {
- position = index
- }
- }
-
- if (position === Infinity) {
- continue
- }
-
- arr = [
- ...arr.slice(0, position),
- ...items,
- ...arr.slice(position, arr.length),
- ]
-
- break
- }
- case 'after': {
- let position = -Infinity
-
- for (const itemMatch of jsonMatch(arr, positionPath)) {
- if (itemMatch.path.length !== 1) {
- continue
- }
- const [segment] = itemMatch.path
- if (typeof segment === 'string') {
- continue
- }
-
- let index: number | undefined
- if (typeof segment === 'number') {
- index = segment
- }
- if (typeof index === 'number' && index < 0) {
- index = arr.length + index
- }
- if (isKeySegment(segment)) {
- index = getIndexForKey(arr, segment._key)
- }
- if (typeof index !== 'number') {
- continue
- }
- if (index > position) {
- position = index
- }
- }
-
- if (position === -Infinity) {
- continue
- }
-
- arr = [
- ...arr.slice(0, position + 1),
- ...items,
- ...arr.slice(position + 1, arr.length),
- ]
-
- break
- }
- default: {
- continue
- }
- }
-
- result = setDeep(result, path, arr)
- }
-
- return ensureArrayKeysDeep(result)
-}
-
-function diffMatchPatch(
- input: unknown,
- pathExpressionValues: {[path: string]: string},
-) {
- const result = Object.entries(pathExpressionValues)
- .flatMap(([pathExpression, dmp]) =>
- Array.from(jsonMatch(input, pathExpression)).map((m) => ({...m, dmp})),
- )
- .filter((i) => i.value !== undefined)
- .map(({path, value, dmp}) => {
- if (typeof value !== 'string') {
- throw new Error(
- `Can't diff-match-patch \`${JSON.stringify(value)}\` at path \`${stringifyPath(path)}\`, because it is not a string`,
- )
- }
-
- const [nextValue] = applyPatches(parsePatch(dmp), value)
- return {path, value: nextValue}
- })
- .reduce((acc, {path, value}) => setDeep(acc, path, value), input as unknown)
-
- return ensureArrayKeysDeep(result)
-}
-
-/**
- * Applies one Sanity patch to the given document, using Content Lake's fixed
- * operation order within a patch (set, setIfMissing, unset, inc, dec, insert,
- * diffMatchPatch). Unresolvable paths are no-ops; a diff-match-patch against
- * a non-string throws, which callers should treat as the whole transaction
- * being rejected.
- */
-export function applyPatchOperations(
- input: unknown,
- operations: SanityPatchOperationRecord,
-): unknown {
- let result = input
- if (operations.set) {
- result = set(result, operations.set)
- }
- if (operations.setIfMissing) {
- result = setIfMissing(result, operations.setIfMissing)
- }
- if (operations.unset) {
- result = unset(result, operations.unset)
- }
- if (operations.inc) {
- result = inc(result, operations.inc)
- }
- if (operations.dec) {
- result = dec(result, operations.dec)
- }
- if (operations.insert) {
- result = insert(result, operations.insert)
- }
- if (operations.diffMatchPatch) {
- result = diffMatchPatch(result, operations.diffMatchPatch)
- }
- return result
-}
diff --git a/packages/plugin-sdk-value/tsconfig.dist.json b/packages/plugin-sdk-value/tsconfig.dist.json
deleted file mode 100644
index 7921a7d58f..0000000000
--- a/packages/plugin-sdk-value/tsconfig.dist.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "extends": "./tsconfig.settings",
- "compilerOptions": {
- "rootDir": "src"
- },
- "include": ["src/**/*.ts"],
- "exclude": ["dist", "node_modules"]
-}
diff --git a/packages/plugin-sdk-value/tsconfig.json b/packages/plugin-sdk-value/tsconfig.json
deleted file mode 100644
index 2246aa9616..0000000000
--- a/packages/plugin-sdk-value/tsconfig.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "extends": "./tsconfig.settings.json",
- "include": ["src"],
- "exclude": ["dist", "node_modules"],
- "compilerOptions": {
- "paths": {
- "@portabletext/editor/test": ["../editor/src/test/_exports/index.ts"],
- "@portabletext/editor/test/vitest": [
- "../editor/src/test/vitest/_exports/index.ts"
- ]
- },
- "rootDir": ".."
- }
-}
diff --git a/packages/plugin-sdk-value/tsconfig.settings.json b/packages/plugin-sdk-value/tsconfig.settings.json
deleted file mode 100644
index 4a5f16452b..0000000000
--- a/packages/plugin-sdk-value/tsconfig.settings.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "extends": "@sanity/tsconfig/strictest",
- "compilerOptions": {
- "rootDir": ".",
- "outDir": "./dist",
- "exactOptionalPropertyTypes": false,
- "noUncheckedIndexedAccess": false
- }
-}
diff --git a/packages/plugin-sdk-value/vitest.config.ts b/packages/plugin-sdk-value/vitest.config.ts
deleted file mode 100644
index c3c2c7859b..0000000000
--- a/packages/plugin-sdk-value/vitest.config.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import react from '@vitejs/plugin-react'
-import {playwright} from '@vitest/browser-playwright'
-import {defineConfig} from 'vitest/config'
-
-export default defineConfig({
- test: {
- projects: [
- {
- // Resolves the monorepo-only `@portabletext/editor/test*` specifiers
- // through this package's tsconfig `paths`.
- resolve: {tsconfigPaths: true},
- plugins: [react({compiler: {target: '19'}})],
- test: {
- name: 'browser',
- include: ['src/**/*.test.tsx'],
- browser: {
- enabled: true,
- headless: true,
- provider: playwright(),
- instances: [
- {
- browser: 'chromium',
- },
- {
- browser: 'firefox',
- },
- {
- browser: 'webkit',
- },
- ],
- screenshotFailures: false,
- },
- },
- },
- {
- // Resolves the monorepo-only `@portabletext/editor/test*` specifiers
- // through this package's tsconfig `paths`.
- resolve: {tsconfigPaths: true},
- plugins: [],
- test: {
- name: 'unit',
- environment: 'node',
- include: ['src/**/*.test.ts'],
- },
- },
- ],
- },
-})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c7984a7c69..330fd6b0b7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -239,9 +239,6 @@ importers:
'@portabletext/plugin-paste-link':
specifier: workspace:*
version: link:../../packages/plugin-paste-link
- '@portabletext/plugin-sdk-value':
- specifier: workspace:*
- version: link:../../packages/plugin-sdk-value
'@portabletext/plugin-table':
specifier: workspace:*
version: link:../../packages/plugin-table
@@ -782,7 +779,7 @@ importers:
version: 19.2.3(@types/react@19.2.17)
'@vitejs/plugin-react':
specifier: catalog:tooling
- version: 6.1.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7)(@babel/runtime@7.29.7)(rolldown@1.2.14)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(oxc-transform-react@0.145.0)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))
+ version: 6.1.1(@rolldown/plugin-babel@0.2.3(@babel/core@8.0.7)(@babel/runtime@7.29.7)(rolldown@1.2.14)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(oxc-transform-react@0.145.0)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))
'@vitest/browser':
specifier: catalog:tooling
version: 5.0.5(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))(vitest@5.0.5)
@@ -1391,88 +1388,6 @@ importers:
specifier: catalog:tooling
version: 5.0.5(@types/node@24.12.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/coverage-v8@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.2.0)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))
- packages/plugin-sdk-value:
- dependencies:
- '@portabletext/patches':
- specifier: workspace:*
- version: link:../patches
- '@sanity/diff-match-patch':
- specifier: 'catalog:'
- version: 3.2.1
- '@sanity/diff-patch':
- specifier: ^6.0.0
- version: 6.0.0
- '@sanity/json-match':
- specifier: ^1.0.5
- version: 1.0.5
- '@xstate/react':
- specifier: 'catalog:'
- version: 6.1.0(@types/react@19.2.17)(react@19.3.1)(xstate@5.33.2)
- obug:
- specifier: 'catalog:'
- version: 3.0.0
- xstate:
- specifier: 'catalog:'
- version: 5.33.2
- devDependencies:
- '@portabletext/editor':
- specifier: workspace:*
- version: link:../editor
- '@portabletext/schema':
- specifier: workspace:^
- version: link:../schema
- '@portabletext/test':
- specifier: workspace:^
- version: link:../test
- '@sanity/pkg-utils':
- specifier: catalog:tooling
- version: 12.3.0(@babel/runtime@7.29.7)(@tsdown/css@0.22.14)(@types/node@24.12.2)(@volar/typescript@2.4.28)(babel-plugin-react-compiler@1.0.0)(oxc-resolver@11.19.1(@emnapi/core@1.11.3)(@emnapi/runtime@1.11.3))(oxc-transform-react@0.145.0)(typescript@7.0.2)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))
- '@sanity/sdk-react':
- specifier: ^3.11.0
- version: 3.11.0(@types/react@19.2.17)(immer@11.0.1)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(use-sync-external-store@1.6.0(react@19.3.1))(vitest@5.0.5)(xstate@5.33.2)
- '@sanity/tsconfig':
- specifier: catalog:tooling
- version: 2.2.1
- '@types/react':
- specifier: ^19.2.17
- version: 19.2.17
- '@types/react-dom':
- specifier: ^19.2.3
- version: 19.2.3(@types/react@19.2.17)
- '@vitejs/plugin-react':
- specifier: catalog:tooling
- version: 6.1.1(@rolldown/plugin-babel@0.2.3(@babel/core@8.0.7)(@babel/runtime@7.29.7)(rolldown@1.2.14)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(oxc-transform-react@0.145.0)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))
- '@vitest/browser':
- specifier: catalog:tooling
- version: 5.0.5(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))(vitest@5.0.5)
- '@vitest/browser-playwright':
- specifier: catalog:tooling
- version: 5.0.5(patch_hash=fff6ae88491c0cebf742bd0969831650fb7662f2c1c7f1f791fa2522af45fbeb)(playwright@1.62.1)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))(vitest@5.0.5)
- jsdom:
- specifier: ^27.2.0
- version: 27.2.0
- oxc-transform-react:
- specifier: catalog:tooling
- version: 0.145.0
- react:
- specifier: 'catalog:'
- version: 19.3.1
- react-dom:
- specifier: 'catalog:'
- version: 19.3.1(react@19.3.1)
- typescript:
- specifier: catalog:tooling
- version: 7.0.2
- vite:
- specifier: catalog:tooling
- version: 8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1)
- vitest:
- specifier: catalog:tooling
- version: 5.0.5(@types/node@24.12.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/coverage-v8@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.2.0)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))
- vitest-browser-react:
- specifier: catalog:tooling
- version: 2.3.0(@types/react-dom@19.2.3(@types/react@19.2.17))(@types/react@19.2.17)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(vitest@5.0.5)
-
packages/plugin-table:
dependencies:
'@floating-ui/dom':
@@ -3920,30 +3835,18 @@ packages:
'@module-federation/error-codes@2.9.0':
resolution: {integrity: sha512-IGpd+VRlji3NyGOGGTsk7YEmPRKcDoBK4YHqIuP+OQwyb2YhHCUHO2vW9RXeQxCuKwi+c6xkTweRYG+Umy+0Zw==}
- '@module-federation/error-codes@2.9.2':
- resolution: {integrity: sha512-MTpKubqsJSBgnuw+2Pli1kHL4INeHD5cGnHL84oRANwQAWK7b6lN3ZZTmL3FL6lYn65ImineqZNqGWBv5GQVLQ==}
-
'@module-federation/managers@2.9.0':
resolution: {integrity: sha512-8KhB2PF4g+M0hGaethU1H4GVWabLn5sF5TvnM6VxgAcDL4TfLY8aC/YobAXHG/SV0jpU5lsGe6s6xy6ccV0MQw==}
'@module-federation/runtime-core@2.9.0':
resolution: {integrity: sha512-dLykRYfpbEJBTdk2NlbNoVVTB196O3qujawTBguLABJkPCWETJNk60NR1yZO34eI+DTH+eGwHU3m7FddAWnbnw==}
- '@module-federation/runtime-core@2.9.2':
- resolution: {integrity: sha512-S9roTDqLtAWaaDBuug69ZnXXGEx0pUq/yG06J759bjRgfAg2P9+dWEv1q7rB2eMIp7HH4L6s3ColDRYdL6tJ9w==}
-
'@module-federation/runtime@2.9.0':
resolution: {integrity: sha512-3cyAav0hWP+dNvB7qrcK9CKxQn+JvkbRvLtZz3zS2g0EyxtDFDjgbHY0Afcf7oHf8IHhKeEdzb/3Kjr1Pjmr7A==}
- '@module-federation/runtime@2.9.2':
- resolution: {integrity: sha512-1lPZVy7TkMTTBMkkjgQt7jA+9FAx226yQqEz+X0lFAIbpxIWfpzNQLD+7IydEe83ZhDJpK3cv/9bn3jjQBZeqQ==}
-
'@module-federation/sdk@2.9.0':
resolution: {integrity: sha512-IMjObgBGQTXd33jTTCYcxvz8iOQGLsZ2QIPOj90rDxuBtJsN4WJwYyXqligrhY/e5p/BipUPdbIgKmWL7zFhTw==}
- '@module-federation/sdk@2.9.2':
- resolution: {integrity: sha512-ILtBFPuYpVcRA/Qay1lJ2hMtZI8fDE/v1n7xiN17e5qx5rSBR3FaamTsmRpN1hIt+gVnoa76CzOP/Y73d8hHNg==}
-
'@module-federation/third-party-dts-extractor@2.9.0':
resolution: {integrity: sha512-R1Xuqnqzw6wQxWV3yU9fX1FydXAeZF2TNVFAVo1N1oLBA2j5y7aUO/Fc3VSNgd9/gxMzJgTVBdA+nMiD2SFCgg==}
@@ -4708,6 +4611,10 @@ packages:
peerDependencies:
react: ^19
+ '@portabletext/sanity-bridge@4.1.5':
+ resolution: {integrity: sha512-6SL23FqPqoX90fc6jITEB3eYm3VYnZ6oERkQM++apTemi5KVuM7TdMPxWtnc7i9wmIYysdN6QDzVI1Vl/DVzkw==}
+ engines: {node: '>=22.12'}
+
'@portabletext/to-html@6.0.0':
resolution: {integrity: sha512-kMqr55pJDBsIyOHLeVccFMFfJxSdozS+A1TeYhiihIinSDhb6ibUxpQIpg0B1n54vZJJW8rDs+QayP3vQqLKUg==}
engines: {node: '>=22.12'}
@@ -5759,12 +5666,6 @@ packages:
react: ^19.2.0
react-dom: ^19.2.0
- '@sanity/sdk-react@3.11.0':
- resolution: {integrity: sha512-yyt8DzzBIKbcAWBsjNJGd4YEPU5N/opBlGOX1DwBPT3LxDJlDsIrmlgJSDMUvAM716dg+Iued3brB+L9bT2VMg==}
- peerDependencies:
- react: ^19.2.0
- react-dom: ^19.2.0
-
'@sanity/sdk@3.0.0':
resolution: {integrity: sha512-RI7WOjgl8mFoj3NelcYq3WPUI9UCAyA76LDwZWQDmN+S+iqjhhQVmWFkTfS6Zij7Pr5rbNhIccYDsMKZb66Qfw==}
@@ -9671,15 +9572,6 @@ packages:
peerDependencies:
react: ^18.0.0 || ^19.0.0
- react-error-boundary@6.1.6:
- resolution: {integrity: sha512-CDXPnXDGyFIbkwaaJ6u+xgsRmJhSi6YdgUDW1vnyKHfXp1a9pfAlM+ZET2CDu80/A+8iRcmXN0NSY9BCCoWP5A==}
- peerDependencies:
- '@types/react': ^19.2.17
- react: ^18.0.0 || ^19.0.0
- peerDependenciesMeta:
- '@types/react':
- optional: true
-
react-fast-compare@3.2.2:
resolution: {integrity: sha512-nsO+KSNgo1SbJqJEYRE9ERzo7YtYbou/OqjSQKxV7jcKox7+usiUVZOAC+XnDOABXggQTno0Y1CpVnuWEc1boQ==}
@@ -13878,8 +13770,6 @@ snapshots:
'@module-federation/error-codes@2.9.0': {}
- '@module-federation/error-codes@2.9.2': {}
-
'@module-federation/managers@2.9.0':
dependencies:
'@module-federation/sdk': 2.9.0
@@ -13889,27 +13779,14 @@ snapshots:
'@module-federation/error-codes': 2.9.0
'@module-federation/sdk': 2.9.0
- '@module-federation/runtime-core@2.9.2':
- dependencies:
- '@module-federation/error-codes': 2.9.2
- '@module-federation/sdk': 2.9.2
-
'@module-federation/runtime@2.9.0':
dependencies:
'@module-federation/error-codes': 2.9.0
'@module-federation/runtime-core': 2.9.0
'@module-federation/sdk': 2.9.0
- '@module-federation/runtime@2.9.2':
- dependencies:
- '@module-federation/error-codes': 2.9.2
- '@module-federation/runtime-core': 2.9.2
- '@module-federation/sdk': 2.9.2
-
'@module-federation/sdk@2.9.0': {}
- '@module-federation/sdk@2.9.2': {}
-
'@module-federation/third-party-dts-extractor@2.9.0': {}
'@module-federation/vite@1.21.6(typescript@7.0.2)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))':
@@ -14400,6 +14277,15 @@ snapshots:
'@portabletext/types': 4.0.2
react: 19.3.1
+ '@portabletext/sanity-bridge@4.1.5(@types/react@19.3.0)(vitest@5.0.5)':
+ dependencies:
+ '@portabletext/schema': link:packages/schema
+ '@sanity/schema': 6.15.0(@types/react@19.3.0)(vitest@5.0.5)
+ '@sanity/types': 6.21.0(@types/react@19.3.0)(vitest@5.0.5)
+ transitivePeerDependencies:
+ - '@types/react'
+ - vitest
+
'@portabletext/to-html@6.0.0':
dependencies:
'@portabletext/toolkit': 6.0.0
@@ -15031,7 +14917,7 @@ snapshots:
'@sanity/generate-help-url': 4.0.0
'@sanity/schema': 6.15.0(@types/react@19.3.0)(vitest@5.0.5)
'@sanity/telemetry': 1.1.0(react@19.3.1)
- '@sanity/types': 6.15.0(@types/react@19.3.0)(vitest@5.0.5)
+ '@sanity/types': 6.21.0(@types/react@19.3.0)(vitest@5.0.5)
'@sanity/workbench-cli': 2.5.2(@rolldown/plugin-babel@0.2.3(@babel/core@8.0.7)(@babel/runtime@7.29.7)(rolldown@1.2.14)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1)))(@types/node@24.12.2)(@types/react@19.3.0)(babel-plugin-react-compiler@1.0.0)(esbuild@0.28.2)(jiti@2.7.0)(oxc-transform-react@0.145.0)(terser@5.44.1)(tsx@4.23.12)(typescript@7.0.2)(vitest@5.0.5)(yaml@2.9.1)
'@vitejs/plugin-react': 6.1.1(@rolldown/plugin-babel@0.2.3(@babel/core@8.0.7)(@babel/runtime@7.29.7)(rolldown@1.2.14)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(oxc-transform-react@0.145.0)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))
chokidar: 5.0.0
@@ -15420,9 +15306,9 @@ snapshots:
'@sanity/media-library-types@1.6.0': {}
- '@sanity/media-library-types@1.8.0(@sanity/types@6.21.0(@types/react@19.2.17)(vitest@5.0.5))':
+ '@sanity/media-library-types@1.8.0(@sanity/types@5.31.2(@types/react@19.3.0))':
dependencies:
- '@sanity/types': 6.21.0(@types/react@19.2.17)(vitest@5.0.5)
+ '@sanity/types': 5.31.2(@types/react@19.3.0)
'@sanity/media-library-types@1.8.0(@sanity/types@6.21.0(@types/react@19.3.0)(vitest@5.0.5))':
dependencies:
@@ -15670,25 +15556,6 @@ snapshots:
- use-sync-external-store
- vitest
- '@sanity/sdk-react@3.11.0(@types/react@19.2.17)(immer@11.0.1)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(use-sync-external-store@1.6.0(react@19.3.1))(vitest@5.0.5)(xstate@5.33.2)':
- dependencies:
- '@module-federation/runtime': 2.9.2
- '@sanity/client': 8.14.1(vitest@5.0.5)
- '@sanity/message-protocol': 0.24.0
- '@sanity/sdk': 3.11.0(@types/react@19.2.17)(immer@11.0.1)(react@19.3.1)(use-sync-external-store@1.6.0(react@19.3.1))(vitest@5.0.5)(xstate@5.33.2)
- '@sanity/types': 6.21.0(@types/react@19.2.17)(vitest@5.0.5)
- react: 19.3.1
- react-compiler-runtime: 1.0.0(react@19.3.1)
- react-dom: 19.3.1(react@19.3.1)
- react-error-boundary: 6.1.6(@types/react@19.2.17)(react@19.3.1)
- rxjs: 7.8.2
- transitivePeerDependencies:
- - '@types/react'
- - immer
- - use-sync-external-store
- - vitest
- - xstate
-
'@sanity/sdk@3.0.0(@types/react@19.3.0)(immer@11.0.1)(react@19.3.1)(use-sync-external-store@1.6.0(react@19.3.1))(vitest@5.0.5)(xstate@5.33.2)':
dependencies:
'@sanity/bifur-client': 1.0.0
@@ -15702,7 +15569,7 @@ snapshots:
'@sanity/message-protocol': 0.24.0
'@sanity/mutate': 0.18.2(vitest@5.0.5)(xstate@5.33.2)
'@sanity/telemetry': 1.1.0(react@19.3.1)
- '@sanity/types': 6.15.0(@types/react@19.3.0)(vitest@5.0.5)
+ '@sanity/types': 6.21.0(@types/react@19.3.0)(vitest@5.0.5)
groq: 3.88.1-typegen-experimental.0
groq-js: 2.0.0
reselect: 5.3.0
@@ -15716,33 +15583,6 @@ snapshots:
- vitest
- xstate
- '@sanity/sdk@3.11.0(@types/react@19.2.17)(immer@11.0.1)(react@19.3.1)(use-sync-external-store@1.6.0(react@19.3.1))(vitest@5.0.5)(xstate@5.33.2)':
- dependencies:
- '@sanity/bifur-client': 2.0.2
- '@sanity/client': 8.14.1(vitest@5.0.5)
- '@sanity/comlink': 4.0.3
- '@sanity/diff-match-patch': 3.2.1
- '@sanity/diff-patch': 7.0.0
- '@sanity/id-utils': 1.1.0
- '@sanity/image-url': 2.1.1
- '@sanity/json-match': 1.0.5
- '@sanity/message-protocol': 0.24.0
- '@sanity/mutate': 0.18.2(vitest@5.0.5)(xstate@5.33.2)
- '@sanity/telemetry': 1.1.0(react@19.3.1)
- '@sanity/types': 6.21.0(@types/react@19.2.17)(vitest@5.0.5)
- groq: 6.20.0
- groq-js: 2.0.1
- reselect: 5.3.0
- rxjs: 7.8.2
- zustand: 5.0.16(@types/react@19.2.17)(immer@11.0.1)(react@19.3.1)(use-sync-external-store@1.6.0(react@19.3.1))
- transitivePeerDependencies:
- - '@types/react'
- - immer
- - react
- - use-sync-external-store
- - vitest
- - xstate
-
'@sanity/sdk@3.11.0(@types/react@19.3.0)(immer@11.0.1)(react@19.3.1)(use-sync-external-store@1.6.0(react@19.3.1))(vitest@5.0.5)(xstate@5.33.2)':
dependencies:
'@sanity/bifur-client': 2.0.2
@@ -15821,7 +15661,7 @@ snapshots:
'@sanity/types@5.31.2(@types/react@19.3.0)':
dependencies:
'@sanity/client': 7.26.2
- '@sanity/media-library-types': 1.6.0
+ '@sanity/media-library-types': 1.8.0(@sanity/types@5.31.2(@types/react@19.3.0))
'@types/react': 19.3.0
'@sanity/types@6.12.0(@types/react@19.3.0)(vitest@5.0.5)':
@@ -15840,14 +15680,6 @@ snapshots:
transitivePeerDependencies:
- vitest
- '@sanity/types@6.21.0(@types/react@19.2.17)(vitest@5.0.5)':
- dependencies:
- '@sanity/client': 8.14.1(vitest@5.0.5)
- '@sanity/media-library-types': 1.8.0(@sanity/types@6.21.0(@types/react@19.2.17)(vitest@5.0.5))
- '@types/react': 19.2.17
- transitivePeerDependencies:
- - vitest
-
'@sanity/types@6.21.0(@types/react@19.3.0)(vitest@5.0.5)':
dependencies:
'@sanity/client': 8.14.1(vitest@5.0.5)
@@ -16005,7 +15837,7 @@ snapshots:
'@module-federation/runtime': 2.9.0
'@module-federation/vite': 1.21.6(typescript@7.0.2)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))
'@sanity/cli-core': 3.8.0(@types/node@24.12.2)(babel-plugin-react-compiler@1.0.0)(esbuild@0.28.2)(oxc-transform-react@0.145.0)(terser@5.44.1)(tsx@4.23.12)(vitest@5.0.5)(yaml@2.9.1)
- '@sanity/types': 6.15.0(@types/react@19.3.0)(vitest@5.0.5)
+ '@sanity/types': 6.21.0(@types/react@19.3.0)(vitest@5.0.5)
'@vitejs/plugin-react': 6.1.1(@rolldown/plugin-babel@0.2.3(@babel/core@8.0.7)(@babel/runtime@7.29.7)(rolldown@1.2.14)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(oxc-transform-react@0.145.0)(vite@8.3.4(@types/node@24.12.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.44.1)(tsx@4.23.12)(yaml@2.9.1))
form-data: 4.0.6
rxjs: 7.8.2
@@ -20266,12 +20098,6 @@ snapshots:
dependencies:
react: 19.3.1
- react-error-boundary@6.1.6(@types/react@19.2.17)(react@19.3.1):
- dependencies:
- react: 19.3.1
- optionalDependencies:
- '@types/react': 19.2.17
-
react-fast-compare@3.2.2: {}
react-focus-lock@2.13.7(@types/react@19.3.0)(react@19.3.1):
@@ -20785,7 +20611,7 @@ snapshots:
'@portabletext/plugin-table': link:packages/plugin-table
'@portabletext/plugin-typography': link:packages/plugin-typography
'@portabletext/react': 8.0.1(react@19.3.1)
- '@portabletext/sanity-bridge': link:packages/sanity-bridge
+ '@portabletext/sanity-bridge': 4.1.5(@types/react@19.3.0)(vitest@5.0.5)
'@portabletext/to-html': 6.0.0
'@portabletext/toolkit': 6.0.0
'@rexxars/react-json-inspector': 9.0.1(react@19.3.1)
@@ -22228,13 +22054,6 @@ snapshots:
react: 19.3.1
use-sync-external-store: 1.6.0(react@19.3.1)
- zustand@5.0.16(@types/react@19.2.17)(immer@11.0.1)(react@19.3.1)(use-sync-external-store@1.6.0(react@19.3.1)):
- optionalDependencies:
- '@types/react': 19.2.17
- immer: 11.0.1
- react: 19.3.1
- use-sync-external-store: 1.6.0(react@19.3.1)
-
zustand@5.0.16(@types/react@19.3.0)(immer@11.0.1)(react@19.3.1)(use-sync-external-store@1.6.0(react@19.3.1)):
optionalDependencies:
'@types/react': 19.3.0