@pm-cm/yjs 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -0
- package/dist/index.cjs +515 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +259 -0
- package/dist/index.d.ts +259 -0
- package/dist/index.js +473 -0
- package/dist/index.js.map +1 -0
- package/package.json +53 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/bridge.ts","../src/types.ts","../src/awareness-proxy.ts","../src/collab-plugins.ts","../src/bridge-sync-plugin.ts","../src/cursor-sync-plugin.ts"],"sourcesContent":["export { createYjsBridge, replaceSharedText, replaceSharedProseMirror } from './bridge.js'\nexport type { YjsBridgeOptions, ReplaceResult, ReplaceTextResult, ReplaceProseMirrorResult } from './bridge.js'\nexport { createAwarenessProxy } from './awareness-proxy.js'\nexport { createCollabPlugins } from './collab-plugins.js'\nexport type { CollabPluginsOptions, ProseMirrorMapping, YCursorPluginOpts, YUndoPluginOpts } from './collab-plugins.js'\nexport {\n ORIGIN_TEXT_TO_PM,\n ORIGIN_PM_TO_TEXT,\n ORIGIN_INIT,\n} from './types.js'\nexport type {\n BootstrapResult,\n YjsBridgeConfig,\n YjsBridgeHandle,\n WarningCode,\n WarningEvent,\n OnWarning,\n} from './types.js'\n\n// Cursor mapping re-exported from @pm-cm/core\nexport { buildCursorMap, cursorMapLookup, reverseCursorMapLookup } from '@pm-cm/core'\nexport type { TextSegment, CursorMap, LocateText } from '@pm-cm/core'\n\n// Bridge sync plugin (auto PM→Y.Text wiring)\nexport { createBridgeSyncPlugin, bridgeSyncPluginKey } from './bridge-sync-plugin.js'\nexport type { BridgeSyncPluginOptions } from './bridge-sync-plugin.js'\n\n// Cursor sync plugin\nexport { createCursorSyncPlugin, cursorSyncPluginKey, syncCmCursor } from './cursor-sync-plugin.js'\nexport type { CursorSyncState, CursorSyncPluginOptions } from './cursor-sync-plugin.js'\n\n// Re-export types from @pm-cm/core\nexport type { Serialize, Parse, Normalize, OnError, ErrorCode, ErrorEvent } from '@pm-cm/core'\n","import type { Node } from 'prosemirror-model'\nimport type { Transaction } from 'prosemirror-state'\nimport { prosemirrorToYXmlFragment, yXmlFragmentToProseMirrorRootNode, ySyncPluginKey } from 'y-prosemirror'\nimport type { Doc, Text as YText, XmlFragment as YXmlFragment } from 'yjs'\nimport type { Normalize, OnError } from '@pm-cm/core'\nimport type { BootstrapResult, YjsBridgeConfig, YjsBridgeHandle } from './types.js'\nimport { ORIGIN_INIT, ORIGIN_TEXT_TO_PM, ORIGIN_PM_TO_TEXT } from './types.js'\n\nconst defaultNormalize: Normalize = (s) => s.replace(/\\r\\n?/g, '\\n')\nconst defaultOnError: OnError = (event) => console.error(`[bridge] ${event.code}: ${event.message}`, event.cause)\n\n/** Result of {@link replaceSharedText}. */\nexport type ReplaceTextResult =\n | { ok: true }\n | { ok: false; reason: 'unchanged' }\n | { ok: false; reason: 'detached' }\n\n/** Result of {@link replaceSharedProseMirror}. */\nexport type ReplaceProseMirrorResult =\n | { ok: true }\n | { ok: false; reason: 'parse-error' }\n | { ok: false; reason: 'detached' }\n\n/**\n * Union of all replace-result types. Kept for backward compatibility.\n * Prefer the narrower {@link ReplaceTextResult} / {@link ReplaceProseMirrorResult}.\n */\nexport type ReplaceResult = ReplaceTextResult | ReplaceProseMirrorResult\n\n/**\n * Replace `Y.Text` content using a minimal diff (common prefix/suffix trimming).\n * Returns a {@link ReplaceResult} indicating success or failure reason.\n */\nexport function replaceSharedText(\n sharedText: YText,\n next: string,\n origin: unknown,\n normalize: Normalize = defaultNormalize,\n): ReplaceTextResult {\n if (!sharedText.doc) {\n return { ok: false, reason: 'detached' }\n }\n\n const normalized = normalize(next)\n const current = sharedText.toString()\n if (current === normalized) {\n return { ok: false, reason: 'unchanged' }\n }\n\n // Minimal diff: find common prefix and suffix, replace only the changed middle.\n let start = 0\n const minLen = Math.min(current.length, normalized.length)\n while (start < minLen && current.charCodeAt(start) === normalized.charCodeAt(start)) {\n start++\n }\n\n let endCurrent = current.length\n let endNext = normalized.length\n while (endCurrent > start && endNext > start && current.charCodeAt(endCurrent - 1) === normalized.charCodeAt(endNext - 1)) {\n endCurrent--\n endNext--\n }\n\n sharedText.doc.transact(() => {\n const deleteCount = endCurrent - start\n if (deleteCount > 0) {\n sharedText.delete(start, deleteCount)\n }\n const insertStr = normalized.slice(start, endNext)\n if (insertStr.length > 0) {\n sharedText.insert(start, insertStr)\n }\n }, origin)\n\n return { ok: true }\n}\n\n/**\n * Replace `Y.XmlFragment` by parsing serialized text into a ProseMirror document.\n * Returns a {@link ReplaceResult} indicating success or failure reason.\n */\nexport function replaceSharedProseMirror(\n doc: Doc,\n fragment: YXmlFragment,\n text: string,\n origin: unknown,\n config: Pick<YjsBridgeConfig, 'schema' | 'parse' | 'normalize' | 'onError'>,\n): ReplaceProseMirrorResult {\n if (!fragment.doc) {\n return { ok: false, reason: 'detached' }\n }\n if (fragment.doc !== doc) {\n throw new Error('fragment belongs to a different Y.Doc than the provided doc')\n }\n\n const normalize = config.normalize ?? defaultNormalize\n const onError = config.onError ?? defaultOnError\n let nextDoc: Node\n try {\n nextDoc = config.parse(normalize(text), config.schema)\n } catch (error) {\n onError({ code: 'parse-error', message: 'failed to parse text into ProseMirror document', cause: error })\n return { ok: false, reason: 'parse-error' }\n }\n\n doc.transact(() => {\n prosemirrorToYXmlFragment(nextDoc, fragment)\n }, origin)\n return { ok: true }\n}\n\n/** Options for {@link createYjsBridge}. */\nexport type YjsBridgeOptions = {\n initialText?: string\n /** Which side wins when both sharedText and sharedProseMirror exist and differ. Default `'text'`. */\n prefer?: 'text' | 'prosemirror'\n}\n\n/**\n * Create a collaborative bridge that keeps `Y.Text` and `Y.XmlFragment` in sync.\n *\n * Runs a synchronous bootstrap to reconcile existing state, then installs a\n * `Y.Text` observer for the text → ProseMirror direction.\n *\n * @throws If `sharedText` or `sharedProseMirror` belong to a different `Y.Doc`.\n */\nexport function createYjsBridge(\n config: YjsBridgeConfig,\n options?: YjsBridgeOptions,\n): YjsBridgeHandle {\n const {\n doc,\n sharedText,\n sharedProseMirror,\n schema,\n serialize,\n parse,\n } = config\n const normalize = config.normalize ?? defaultNormalize\n const onError = config.onError ?? defaultOnError\n\n if (!sharedText.doc) {\n throw new Error('sharedText is not attached to any Y.Doc')\n }\n if (sharedText.doc !== doc) {\n throw new Error('sharedText belongs to a different Y.Doc than the provided doc')\n }\n if (!sharedProseMirror.doc) {\n throw new Error('sharedProseMirror is not attached to any Y.Doc')\n }\n if (sharedProseMirror.doc !== doc) {\n throw new Error('sharedProseMirror belongs to a different Y.Doc than the provided doc')\n }\n\n let lastBridgedText: string | null = null\n\n /** Returns `true` if the parse succeeded. */\n const syncTextToProsemirror = (origin: unknown): boolean => {\n const text = normalize(sharedText.toString())\n if (lastBridgedText === text) {\n return true\n }\n\n const result = replaceSharedProseMirror(doc, sharedProseMirror, text, origin, {\n schema,\n parse,\n normalize,\n onError,\n })\n if (result.ok) {\n lastBridgedText = text\n }\n return result.ok\n }\n\n const sharedProseMirrorToText = (fragment: YXmlFragment): string | null => {\n try {\n const pmDoc = yXmlFragmentToProseMirrorRootNode(fragment, schema)\n return normalize(serialize(pmDoc))\n } catch (error) {\n onError({ code: 'serialize-error', message: 'failed to convert ProseMirror fragment to text', cause: error })\n return null\n }\n }\n\n // Bootstrap\n const bootstrap = (): BootstrapResult => {\n const text = normalize(sharedText.toString())\n const hasText = text.length > 0\n const hasProsemirror = sharedProseMirror.length > 0\n\n if (!hasText && !hasProsemirror) {\n const initial = options?.initialText ?? ''\n if (initial.length > 0) {\n // Set Y.XmlFragment first, then derive Y.Text from serialize(parse(initial))\n // to ensure both shared types are in the same canonical form.\n const initResult = replaceSharedProseMirror(doc, sharedProseMirror, initial, ORIGIN_INIT, {\n schema,\n parse,\n normalize,\n onError,\n })\n if (!initResult.ok) {\n return { source: 'initial', parseError: true }\n }\n const pmDoc = yXmlFragmentToProseMirrorRootNode(sharedProseMirror, schema)\n const canonicalText = serialize(pmDoc)\n replaceSharedText(sharedText, canonicalText, ORIGIN_INIT, normalize)\n lastBridgedText = normalize(canonicalText)\n return { source: 'initial' }\n }\n return { source: 'empty' }\n }\n\n if (hasText && !hasProsemirror) {\n const ok = syncTextToProsemirror(ORIGIN_INIT)\n return { source: 'text', ...(!ok && { parseError: true }) }\n }\n\n if (!hasText && hasProsemirror) {\n const textFromProsemirror = sharedProseMirrorToText(sharedProseMirror)\n if (textFromProsemirror !== null) {\n replaceSharedText(sharedText, textFromProsemirror, ORIGIN_INIT, normalize)\n lastBridgedText = normalize(textFromProsemirror)\n return { source: 'prosemirror' }\n }\n return { source: 'prosemirror', parseError: true }\n }\n\n const prosemirrorText = sharedProseMirrorToText(sharedProseMirror)\n if (prosemirrorText === null) {\n const fallbackText = hasText ? text : (options?.initialText ?? '')\n let parseError = false\n if (fallbackText.length > 0) {\n replaceSharedText(sharedText, fallbackText, ORIGIN_INIT, normalize)\n const fallbackResult = replaceSharedProseMirror(doc, sharedProseMirror, fallbackText, ORIGIN_INIT, {\n schema,\n parse,\n normalize,\n onError,\n })\n if (!fallbackResult.ok) parseError = true\n }\n return { source: 'text', ...(parseError && { parseError: true }) }\n }\n\n if (prosemirrorText !== text) {\n const prefer = options?.prefer ?? 'text'\n if (prefer === 'prosemirror') {\n replaceSharedText(sharedText, prosemirrorText, ORIGIN_INIT, normalize)\n lastBridgedText = normalize(prosemirrorText)\n return { source: 'prosemirror' }\n } else {\n const ok = syncTextToProsemirror(ORIGIN_INIT)\n return { source: 'text', ...(!ok && { parseError: true }) }\n }\n } else {\n lastBridgedText = text\n return { source: 'both-match' }\n }\n }\n\n const textObserver = (\n _: unknown,\n transaction: { origin: unknown },\n ) => {\n if (transaction.origin === ORIGIN_PM_TO_TEXT || transaction.origin === ORIGIN_INIT) {\n return\n }\n\n syncTextToProsemirror(ORIGIN_TEXT_TO_PM)\n }\n\n // Run bootstrap synchronously before installing the observer so that\n // an exception during bootstrap cannot leave a dangling observer.\n const bootstrapResult = bootstrap()\n\n sharedText.observe(textObserver)\n\n return {\n bootstrapResult,\n syncToSharedText(doc: Node): ReplaceTextResult {\n const text = serialize(doc)\n const result = replaceSharedText(sharedText, text, ORIGIN_PM_TO_TEXT, normalize)\n // Always update lastBridgedText unless truly failed (detached).\n // 'unchanged' means Y.Text already has this content — still need to\n // record it so the reverse observer doesn't trigger a redundant sync.\n if (result.ok || result.reason === 'unchanged') {\n lastBridgedText = normalize(text)\n }\n return result\n },\n isYjsSyncChange(tr: Transaction): boolean {\n // Internal meta shape from y-prosemirror's ySyncPlugin (tested against ^1.3.x).\n const meta = tr.getMeta(ySyncPluginKey)\n return (\n typeof meta === 'object' &&\n meta !== null &&\n 'isChangeOrigin' in meta &&\n (meta as Record<string, unknown>).isChangeOrigin === true\n )\n },\n dispose() {\n sharedText.unobserve(textObserver)\n },\n }\n}\n","import type { Node, Schema } from 'prosemirror-model'\nimport type { Transaction } from 'prosemirror-state'\nimport type { Serialize, Parse, Normalize, OnError } from '@pm-cm/core'\nimport type { Doc, Text as YText, XmlFragment as YXmlFragment } from 'yjs'\nimport type { ReplaceTextResult } from './bridge.js'\n\n/** Known warning codes emitted by the yjs bridge and plugins. */\nexport type WarningCode = 'bridge-already-wired' | 'sync-failed' | 'ysync-plugin-missing' | 'cursor-sync-not-installed'\n\n/** Structured warning event for non-fatal warnings. */\nexport type WarningEvent = {\n code: WarningCode\n message: string\n}\n\n/**\n * Warning handler callback for non-fatal warnings.\n *\n * Known codes:\n * - `'bridge-already-wired'` — the same bridge handle is wired to multiple plugin instances.\n * - `'sync-failed'` — `syncToSharedText` failed (e.g. Y.Text detached).\n * - `'ysync-plugin-missing'` — ySyncPlugin state is not available; cursor broadcast skipped.\n * - `'cursor-sync-not-installed'` — cursor sync plugin is not installed on the EditorView.\n */\nexport type OnWarning = (event: WarningEvent) => void\n\n/** Yjs transaction origin: text → ProseMirror direction. */\nexport const ORIGIN_TEXT_TO_PM = 'bridge:text-to-prosemirror'\n\n/** Yjs transaction origin: ProseMirror → text direction. */\nexport const ORIGIN_PM_TO_TEXT = 'bridge:prosemirror-to-text'\n\n/** Yjs transaction origin: bootstrap initialization. */\nexport const ORIGIN_INIT = 'bridge:init'\n\n/** Configuration for {@link createYjsBridge}. */\nexport type YjsBridgeConfig = {\n doc: Doc\n sharedText: YText\n sharedProseMirror: YXmlFragment\n schema: Schema\n serialize: Serialize\n parse: Parse\n normalize?: Normalize\n /** Called on non-fatal errors (e.g. parse failures). Defaults to `console.error`. */\n onError?: OnError\n}\n\n/**\n * Result of the bootstrap phase in {@link createYjsBridge}.\n * Indicates which source was used to initialize the shared types.\n */\nexport type BootstrapResult = {\n source: 'text' | 'prosemirror' | 'both-match' | 'empty' | 'initial'\n /** `true` when format conversion (parse or serialize) failed during bootstrap. The bridge is still usable but the affected shared type may be stale. */\n parseError?: boolean\n}\n\n/** Handle returned by {@link createYjsBridge}. */\nexport type YjsBridgeHandle = {\n /** Result of the synchronous bootstrap phase. */\n readonly bootstrapResult: BootstrapResult\n /** Serialize `doc` and push to `Y.Text` using minimal diff. */\n syncToSharedText(doc: Node): ReplaceTextResult\n /** Returns `true` if the transaction originated from `y-prosemirror` sync. */\n isYjsSyncChange(tr: Transaction): boolean\n /** Remove the Y.Text observer. Call when tearing down. */\n dispose(): void\n}\n","import type { Awareness } from 'y-protocols/awareness'\n\n/**\n * Create a Proxy around a Yjs {@link Awareness} that suppresses the specified\n * cursor field. This prevents y-prosemirror's built-in cursor management from\n * conflicting with the PM↔CM cursor sync plugin.\n *\n * Other `setLocalStateField` calls are passed through unchanged.\n */\nexport function createAwarenessProxy(awareness: Awareness, cursorField = 'pmCursor'): Awareness {\n return new Proxy(awareness, {\n get(target, prop, receiver) {\n if (prop === 'getLocalState') {\n return () => {\n const state = target.getLocalState()\n return state ? { ...state, [cursorField]: null } : state\n }\n }\n if (prop === 'setLocalStateField') {\n return (field: string, value: unknown) => {\n // Only suppress the cursor field; pass through other fields\n if (field === cursorField) return\n target.setLocalStateField(field, value)\n }\n }\n const value = Reflect.get(target, prop, receiver) as unknown\n return typeof value === 'function' ? (value as Function).bind(target) : value\n },\n }) as Awareness\n}\n","import type { Node, Schema } from 'prosemirror-model'\nimport type { EditorState, Plugin } from 'prosemirror-state'\nimport type { DecorationAttrs } from 'prosemirror-view'\nimport type { Awareness } from 'y-protocols/awareness'\nimport type { Serialize, LocateText } from '@pm-cm/core'\nimport { initProseMirrorDoc, yCursorPlugin, ySyncPlugin, yUndoPlugin } from 'y-prosemirror'\nimport type { AbstractType, Text as YText, UndoManager } from 'yjs'\nimport type { XmlFragment as YXmlFragment } from 'yjs'\nimport { createAwarenessProxy } from './awareness-proxy.js'\nimport { createBridgeSyncPlugin } from './bridge-sync-plugin.js'\nimport { createCursorSyncPlugin } from './cursor-sync-plugin.js'\nimport type { YjsBridgeHandle, OnWarning } from './types.js'\n\n/** Yjs ↔ ProseMirror node mapping used by `y-prosemirror`. */\nexport type ProseMirrorMapping = Map<AbstractType<unknown>, Node | Node[]>\n\n/** Options forwarded to `yCursorPlugin` from y-prosemirror. */\nexport type YCursorPluginOpts = {\n awarenessStateFilter?: (currentClientId: number, userClientId: number, user: unknown) => boolean\n cursorBuilder?: (user: unknown, clientId: number) => HTMLElement\n selectionBuilder?: (user: unknown, clientId: number) => DecorationAttrs\n getSelection?: (state: EditorState) => unknown\n}\n\n/** Options forwarded to `yUndoPlugin` from y-prosemirror. */\nexport type YUndoPluginOpts = {\n protectedNodes?: Set<string>\n trackedOrigins?: unknown[]\n undoManager?: UndoManager | null\n}\n\n/** Options for {@link createCollabPlugins}. */\nexport type CollabPluginsOptions = {\n /** Shared ProseMirror document in Yjs. */\n sharedProseMirror: YXmlFragment\n awareness: Awareness\n cursorFieldName?: string\n serialize?: Serialize\n /** Awareness field used for CM/Y.Text cursor payloads. Default `'cursor'`. */\n cmCursorFieldName?: string\n locate?: LocateText\n /**\n * Enable PM↔CM cursor sync. Default `false`.\n *\n * When enabled, an {@link createAwarenessProxy | awareness proxy} is applied\n * to suppress y-prosemirror's built-in cursor management.\n */\n cursorSync?: boolean\n /**\n * The shared `Y.Text` instance. When provided, the cursor sync plugin also\n * broadcasts CM-format cursor positions so remote `yCollab` instances render them.\n */\n sharedText?: YText\n /**\n * When provided, a bridge sync plugin is inserted before the cursor sync plugin\n * to ensure Y.Text is synced before cursor positions are computed. This guarantees\n * that serialize-based offsets match Y.Text indices.\n */\n bridge?: YjsBridgeHandle\n /** Extra options forwarded to `yCursorPlugin`. */\n yCursorPluginOpts?: YCursorPluginOpts\n /** Extra options forwarded to `yUndoPlugin`. */\n yUndoPluginOpts?: YUndoPluginOpts\n /** Called for non-fatal warnings. Propagated to child plugins. Default `console.warn`. */\n onWarning?: OnWarning\n}\n\n/**\n * Bundle `ySyncPlugin`, `yCursorPlugin`, `yUndoPlugin` from y-prosemirror,\n * plus an optional PM↔CM cursor sync plugin.\n *\n * @throws If `cursorSync: true` but `serialize` is not provided.\n */\nexport function createCollabPlugins(\n schema: Schema,\n options: CollabPluginsOptions,\n): { plugins: Plugin[]; doc: Node; mapping: ProseMirrorMapping } {\n const cursorFieldName = options.cursorFieldName ?? 'pmCursor'\n const enableCursorSync = options.cursorSync ?? false\n const { sharedProseMirror } = options\n\n if (enableCursorSync && !options.serialize) {\n throw new Error('createCollabPlugins: cursorSync requires serialize to be provided')\n }\n const { doc, mapping: rawMapping } = initProseMirrorDoc(sharedProseMirror, schema)\n const mapping = rawMapping as ProseMirrorMapping\n const pmAwareness = enableCursorSync\n ? createAwarenessProxy(options.awareness, cursorFieldName)\n : options.awareness\n\n const plugins: Plugin[] = [\n ySyncPlugin(sharedProseMirror, { mapping: rawMapping }),\n yCursorPlugin(pmAwareness, options.yCursorPluginOpts ?? {}, cursorFieldName),\n yUndoPlugin(options.yUndoPluginOpts),\n ]\n\n // Bridge sync plugin must run before cursor sync plugin so that\n // Y.Text is updated before cursor positions are computed.\n if (options.bridge) {\n plugins.push(createBridgeSyncPlugin(options.bridge, { onWarning: options.onWarning }))\n }\n\n if (enableCursorSync && options.serialize) {\n plugins.push(\n createCursorSyncPlugin({\n awareness: options.awareness,\n serialize: options.serialize,\n cursorFieldName,\n cmCursorFieldName: options.cmCursorFieldName,\n locate: options.locate,\n sharedText: options.sharedText,\n onWarning: options.onWarning,\n }),\n )\n }\n\n return { plugins, doc, mapping }\n}\n","import { Plugin, PluginKey } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\nimport type { YjsBridgeHandle, OnWarning } from './types.js'\n\ntype BridgeSyncState = { needsSync: boolean }\n\ntype BridgeSyncFailure = { ok: false; reason: 'detached' }\n\n/** Options for {@link createBridgeSyncPlugin}. */\nexport type BridgeSyncPluginOptions = {\n /** Called when `syncToSharedText` fails (excludes `reason: 'unchanged'`). */\n onSyncFailure?: (result: BridgeSyncFailure, view: EditorView) => void\n /** Called for non-fatal warnings. Default `console.warn`. */\n onWarning?: OnWarning\n}\n\n/** ProseMirror plugin key for {@link createBridgeSyncPlugin}. Use to read the plugin state. */\nexport const bridgeSyncPluginKey = new PluginKey<BridgeSyncState>('pm-cm-bridge-sync')\n\nconst wiredBridges = new WeakSet<YjsBridgeHandle>()\n\nconst defaultOnWarning: OnWarning = (event) => console.warn(`[pm-cm] ${event.code}: ${event.message}`)\n\n/**\n * ProseMirror plugin that automatically syncs PM doc changes to Y.Text\n * via the bridge handle. Skips Yjs-originated changes to avoid loops.\n *\n * A warning is logged if the same bridge handle is wired more than once.\n * The guard is cleaned up when the plugin is destroyed.\n */\nexport function createBridgeSyncPlugin(\n bridge: YjsBridgeHandle,\n options: BridgeSyncPluginOptions = {},\n): Plugin {\n const warn = options.onWarning ?? defaultOnWarning\n if (wiredBridges.has(bridge)) {\n warn({ code: 'bridge-already-wired', message: 'this bridge is already wired to another plugin instance' })\n }\n wiredBridges.add(bridge)\n\n return new Plugin<BridgeSyncState>({\n key: bridgeSyncPluginKey,\n\n state: {\n init(): BridgeSyncState {\n return { needsSync: false }\n },\n apply(tr, _prev): BridgeSyncState {\n if (!tr.docChanged) return { needsSync: false }\n if (bridge.isYjsSyncChange(tr)) return { needsSync: false }\n return { needsSync: true }\n },\n },\n\n view() {\n return {\n update(view) {\n const state = bridgeSyncPluginKey.getState(view.state)\n if (state?.needsSync) {\n const result = bridge.syncToSharedText(view.state.doc)\n if (!result.ok) {\n if (result.reason === 'detached') {\n options.onSyncFailure?.(result, view)\n warn({ code: 'sync-failed', message: `bridge sync failed: ${result.reason}` })\n }\n }\n }\n },\n destroy() {\n wiredBridges.delete(bridge)\n },\n }\n },\n })\n}\n","import { Plugin, PluginKey } from 'prosemirror-state'\nimport type { Node } from 'prosemirror-model'\nimport type { EditorView } from 'prosemirror-view'\nimport type { Awareness } from 'y-protocols/awareness'\nimport { absolutePositionToRelativePosition, ySyncPluginKey } from 'y-prosemirror'\nimport { createRelativePositionFromTypeIndex } from 'yjs'\nimport type { Text as YText, XmlFragment as YXmlFragment } from 'yjs'\nimport type { Serialize, LocateText, CursorMap } from '@pm-cm/core'\nimport { buildCursorMap, cursorMapLookup, reverseCursorMapLookup } from '@pm-cm/core'\nimport type { OnWarning } from './types.js'\n\n/** Plugin state for the cursor sync plugin. Read via {@link cursorSyncPluginKey}. */\nexport type CursorSyncState = {\n /** Pending CodeMirror cursor to broadcast. Set by {@link syncCmCursor}. */\n pendingCm: { anchor: number; head: number } | null\n /** Text offset mapped from the current PM selection anchor. `null` when no mapping is available. */\n mappedTextOffset: number | null\n}\n\n/** ProseMirror plugin key for {@link createCursorSyncPlugin}. Use to read the plugin state. */\nexport const cursorSyncPluginKey = new PluginKey<CursorSyncState>('pm-cm-cursor-sync')\n\n/**\n * Internal shape of `ySyncPluginKey` state from y-prosemirror.\n * Not exported by upstream — kept here for explicit tracking.\n * Tested against y-prosemirror ^1.3.x.\n */\ntype YSyncPluginState = { type: YXmlFragment; binding: { mapping: Map<unknown, unknown> } }\n\nfunction getYSyncState(view: EditorView): YSyncPluginState | null {\n const raw = ySyncPluginKey.getState(view.state) as Record<string, unknown> | undefined\n if (!raw) return null\n if (\n typeof raw === 'object' &&\n 'type' in raw && raw.type &&\n 'binding' in raw && raw.binding &&\n typeof raw.binding === 'object' &&\n 'mapping' in (raw.binding as Record<string, unknown>) &&\n (raw.binding as Record<string, unknown>).mapping instanceof Map\n ) {\n return raw as unknown as YSyncPluginState\n }\n return null\n}\n\nfunction toRelativePosition(\n view: EditorView,\n pmPos: number,\n): unknown | null {\n const ySyncState = getYSyncState(view)\n if (!ySyncState) return null\n\n return absolutePositionToRelativePosition(\n pmPos,\n ySyncState.type,\n ySyncState.binding.mapping as any, // eslint-disable-line @typescript-eslint/no-explicit-any -- y-prosemirror internal mapping type\n )\n}\n\n/** Returns `false` when ySyncPlugin state is unavailable (plugin not installed). */\nfunction broadcastPmCursor(\n awareness: Awareness,\n cursorFieldName: string,\n view: EditorView,\n pmAnchor: number,\n pmHead: number,\n): boolean {\n const relAnchor = toRelativePosition(view, pmAnchor)\n const relHead = toRelativePosition(view, pmHead)\n if (relAnchor === null || relHead === null) return false\n\n awareness.setLocalStateField(cursorFieldName, { anchor: relAnchor, head: relHead })\n return true\n}\n\nfunction broadcastTextCursor(\n awareness: Awareness,\n cmCursorFieldName: string,\n sharedText: YText,\n textAnchor: number,\n textHead: number,\n): void {\n const len = sharedText.length\n const clamp = (v: number) => Math.max(0, Math.min(v, len))\n const relAnchor = createRelativePositionFromTypeIndex(sharedText, clamp(textAnchor))\n const relHead = createRelativePositionFromTypeIndex(sharedText, clamp(textHead))\n awareness.setLocalStateField(cmCursorFieldName, { anchor: relAnchor, head: relHead })\n}\n\nconst defaultOnWarning: OnWarning = (event) => console.warn(`[pm-cm] ${event.code}: ${event.message}`)\n\n/** Options for {@link createCursorSyncPlugin}. */\nexport type CursorSyncPluginOptions = {\n awareness: Awareness\n serialize: Serialize\n cursorFieldName?: string\n /** Awareness field used for CM/Y.Text cursor payloads. Default `'cursor'`. */\n cmCursorFieldName?: string\n locate?: LocateText\n /**\n * When provided, the plugin also broadcasts CM-format cursor positions\n * (Y.Text relative positions) to the awareness field specified by\n * `cmCursorFieldName`, so that remote `yCollab` instances can render the cursor.\n */\n sharedText?: YText\n /** Called for non-fatal warnings. Default `console.warn`. */\n onWarning?: OnWarning\n}\n\n/**\n * ProseMirror plugin that synchronizes cursor positions between PM and CM via Yjs awareness.\n *\n * - PM → awareness: automatically broadcasts when the PM view is focused and selection changes.\n * - CM → awareness: triggered by dispatching {@link syncCmCursor}.\n */\nexport function createCursorSyncPlugin(options: CursorSyncPluginOptions): Plugin {\n const { awareness, serialize, locate, sharedText } = options\n const warn = options.onWarning ?? defaultOnWarning\n const cursorFieldName = options.cursorFieldName ?? 'pmCursor'\n const cmCursorFieldName = options.cmCursorFieldName ?? 'cursor'\n\n let warnedSyncPluginMissing = false\n\n // Cached cursor map (serialize-based) — rebuilt only when doc changes\n let cachedMap: CursorMap | null = null\n let cachedMapDoc: Node | null = null\n\n function getOrBuildMap(doc: Node): CursorMap {\n if (cachedMapDoc !== doc || !cachedMap) {\n cachedMap = buildCursorMap(doc, serialize, locate)\n cachedMapDoc = doc\n }\n return cachedMap\n }\n\n return new Plugin<CursorSyncState>({\n key: cursorSyncPluginKey,\n\n state: {\n init(): CursorSyncState {\n return { pendingCm: null, mappedTextOffset: null }\n },\n apply(tr, prev, _oldState, newState): CursorSyncState {\n const cmMeta = tr.getMeta(cursorSyncPluginKey) as\n | { anchor: number; head: number }\n | undefined\n if (cmMeta) {\n return { pendingCm: cmMeta, mappedTextOffset: prev.mappedTextOffset }\n }\n\n // Compute PM → text offset when selection or doc changes\n let mappedTextOffset = prev.mappedTextOffset\n if (tr.selectionSet || tr.docChanged) {\n const map = getOrBuildMap(newState.doc)\n mappedTextOffset = cursorMapLookup(map, newState.selection.anchor)\n }\n\n return {\n pendingCm: prev.pendingCm !== null ? null : prev.pendingCm,\n mappedTextOffset,\n }\n },\n },\n\n view() {\n return {\n update(view, prevState) {\n const pluginState = cursorSyncPluginKey.getState(view.state)\n const prevPluginState = cursorSyncPluginKey.getState(prevState)\n\n // CM → awareness: broadcast when pendingCm is newly set\n if (\n pluginState?.pendingCm != null &&\n pluginState.pendingCm !== prevPluginState?.pendingCm\n ) {\n const map = getOrBuildMap(view.state.doc)\n const pmAnchor = reverseCursorMapLookup(map, pluginState.pendingCm.anchor)\n const pmHead = reverseCursorMapLookup(map, pluginState.pendingCm.head)\n if (pmAnchor !== null && pmHead !== null) {\n const ok = broadcastPmCursor(awareness, cursorFieldName, view, pmAnchor, pmHead)\n if (!ok && !warnedSyncPluginMissing) {\n warnedSyncPluginMissing = true\n warn({ code: 'ysync-plugin-missing', message: 'ySyncPlugin state not available — cursor broadcast skipped' })\n }\n }\n // Also broadcast CM-format cursor so remote yCollab can render it\n if (sharedText) {\n broadcastTextCursor(\n awareness,\n cmCursorFieldName,\n sharedText,\n pluginState.pendingCm.anchor,\n pluginState.pendingCm.head,\n )\n }\n return\n }\n\n // PM → awareness: auto-broadcast on selection/doc change when focused\n if (\n view.hasFocus() &&\n (view.state.selection !== prevState.selection ||\n view.state.doc !== prevState.doc)\n ) {\n const { anchor, head } = view.state.selection\n const ok = broadcastPmCursor(awareness, cursorFieldName, view, anchor, head)\n if (!ok && !warnedSyncPluginMissing) {\n warnedSyncPluginMissing = true\n warn({ code: 'ysync-plugin-missing', message: 'ySyncPlugin state not available — cursor broadcast skipped' })\n }\n // Also broadcast CM-format cursor so remote yCollab can render it.\n // When bridgeSyncPlugin runs before this plugin, Y.Text is already\n // synced so serialize-based offsets match Y.Text indices.\n if (sharedText) {\n const map = getOrBuildMap(view.state.doc)\n const textAnchor = cursorMapLookup(map, anchor)\n const textHead = cursorMapLookup(map, head)\n if (textAnchor !== null && textHead !== null) {\n broadcastTextCursor(awareness, cmCursorFieldName, sharedText, textAnchor, textHead)\n }\n }\n }\n },\n }\n },\n })\n}\n\n/**\n * Dispatch a CodeMirror cursor offset (or range) to the cursor sync plugin.\n * The plugin will convert it to a ProseMirror position and broadcast via awareness.\n *\n * @param view - The ProseMirror EditorView that has the cursor sync plugin installed.\n * @param anchor - CodeMirror text offset for the anchor.\n * @param head - CodeMirror text offset for the head (defaults to `anchor` for a collapsed cursor).\n * @param onWarning - Optional warning callback. Default `console.warn`.\n */\nexport function syncCmCursor(view: EditorView, anchor: number, head?: number, onWarning?: OnWarning): void {\n if (!cursorSyncPluginKey.getState(view.state)) {\n (onWarning ?? defaultOnWarning)({ code: 'cursor-sync-not-installed', message: 'cursor sync plugin is not installed on this EditorView' })\n return\n }\n const sanitize = (v: number) => Math.max(0, Math.floor(v))\n view.dispatch(\n view.state.tr.setMeta(cursorSyncPluginKey, {\n anchor: sanitize(anchor),\n head: sanitize(head ?? anchor),\n }),\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,2BAA6F;;;ACyBtF,IAAM,oBAAoB;AAG1B,IAAM,oBAAoB;AAG1B,IAAM,cAAc;;;ADzB3B,IAAM,mBAA8B,CAAC,MAAM,EAAE,QAAQ,UAAU,IAAI;AACnE,IAAM,iBAA0B,CAAC,UAAU,QAAQ,MAAM,YAAY,MAAM,IAAI,KAAK,MAAM,OAAO,IAAI,MAAM,KAAK;AAwBzG,SAAS,kBACd,YACA,MACA,QACA,YAAuB,kBACJ;AACnB,MAAI,CAAC,WAAW,KAAK;AACnB,WAAO,EAAE,IAAI,OAAO,QAAQ,WAAW;AAAA,EACzC;AAEA,QAAM,aAAa,UAAU,IAAI;AACjC,QAAM,UAAU,WAAW,SAAS;AACpC,MAAI,YAAY,YAAY;AAC1B,WAAO,EAAE,IAAI,OAAO,QAAQ,YAAY;AAAA,EAC1C;AAGA,MAAI,QAAQ;AACZ,QAAM,SAAS,KAAK,IAAI,QAAQ,QAAQ,WAAW,MAAM;AACzD,SAAO,QAAQ,UAAU,QAAQ,WAAW,KAAK,MAAM,W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,eAAe;AAAA,EACrC;AAIA,MAAI,QAAQ,QAAQ;AAClB,YAAQ,KAAK,uBAAuB,QAAQ,QAAQ,EAAE,WAAW,QAAQ,UAAU,CAAC,CAAC;AAAA,EACvF;AAEA,MAAI,oBAAoB,QAAQ,WAAW;AACzC,YAAQ;AAAA,MACN,uBAAuB;AAAA,QACrB,WAAW,QAAQ;AAAA,QACnB,WAAW,QAAQ;AAAA,QACnB;AAAA,QACA,mBAAmB,QAAQ;AAAA,QAC3B,QAAQ,QAAQ;AAAA,QAChB,YAAY,QAAQ;AAAA,QACpB,WAAW,QAAQ;AAAA,MACrB,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,KAAK,QAAQ;AACjC;;;AJjGA,IAAAC,eAAwE;","names":["doc","value","import_y_prosemirror","import_prosemirror_state","import_y_prosemirror","defaultOnWarning","import_core"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { Doc, Text, XmlFragment, UndoManager, AbstractType } from 'yjs';
|
|
2
|
+
import { Serialize, Parse, Normalize, OnError, LocateText } from '@pm-cm/core';
|
|
3
|
+
export { CursorMap, ErrorCode, ErrorEvent, LocateText, Normalize, OnError, Parse, Serialize, TextSegment, buildCursorMap, cursorMapLookup, reverseCursorMapLookup } from '@pm-cm/core';
|
|
4
|
+
import { Node, Schema } from 'prosemirror-model';
|
|
5
|
+
import { Transaction, EditorState, Plugin, PluginKey } from 'prosemirror-state';
|
|
6
|
+
import { Awareness } from 'y-protocols/awareness';
|
|
7
|
+
import { DecorationAttrs, EditorView } from 'prosemirror-view';
|
|
8
|
+
|
|
9
|
+
/** Known warning codes emitted by the yjs bridge and plugins. */
|
|
10
|
+
type WarningCode = 'bridge-already-wired' | 'sync-failed' | 'ysync-plugin-missing' | 'cursor-sync-not-installed';
|
|
11
|
+
/** Structured warning event for non-fatal warnings. */
|
|
12
|
+
type WarningEvent = {
|
|
13
|
+
code: WarningCode;
|
|
14
|
+
message: string;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Warning handler callback for non-fatal warnings.
|
|
18
|
+
*
|
|
19
|
+
* Known codes:
|
|
20
|
+
* - `'bridge-already-wired'` — the same bridge handle is wired to multiple plugin instances.
|
|
21
|
+
* - `'sync-failed'` — `syncToSharedText` failed (e.g. Y.Text detached).
|
|
22
|
+
* - `'ysync-plugin-missing'` — ySyncPlugin state is not available; cursor broadcast skipped.
|
|
23
|
+
* - `'cursor-sync-not-installed'` — cursor sync plugin is not installed on the EditorView.
|
|
24
|
+
*/
|
|
25
|
+
type OnWarning = (event: WarningEvent) => void;
|
|
26
|
+
/** Yjs transaction origin: text → ProseMirror direction. */
|
|
27
|
+
declare const ORIGIN_TEXT_TO_PM = "bridge:text-to-prosemirror";
|
|
28
|
+
/** Yjs transaction origin: ProseMirror → text direction. */
|
|
29
|
+
declare const ORIGIN_PM_TO_TEXT = "bridge:prosemirror-to-text";
|
|
30
|
+
/** Yjs transaction origin: bootstrap initialization. */
|
|
31
|
+
declare const ORIGIN_INIT = "bridge:init";
|
|
32
|
+
/** Configuration for {@link createYjsBridge}. */
|
|
33
|
+
type YjsBridgeConfig = {
|
|
34
|
+
doc: Doc;
|
|
35
|
+
sharedText: Text;
|
|
36
|
+
sharedProseMirror: XmlFragment;
|
|
37
|
+
schema: Schema;
|
|
38
|
+
serialize: Serialize;
|
|
39
|
+
parse: Parse;
|
|
40
|
+
normalize?: Normalize;
|
|
41
|
+
/** Called on non-fatal errors (e.g. parse failures). Defaults to `console.error`. */
|
|
42
|
+
onError?: OnError;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Result of the bootstrap phase in {@link createYjsBridge}.
|
|
46
|
+
* Indicates which source was used to initialize the shared types.
|
|
47
|
+
*/
|
|
48
|
+
type BootstrapResult = {
|
|
49
|
+
source: 'text' | 'prosemirror' | 'both-match' | 'empty' | 'initial';
|
|
50
|
+
/** `true` when format conversion (parse or serialize) failed during bootstrap. The bridge is still usable but the affected shared type may be stale. */
|
|
51
|
+
parseError?: boolean;
|
|
52
|
+
};
|
|
53
|
+
/** Handle returned by {@link createYjsBridge}. */
|
|
54
|
+
type YjsBridgeHandle = {
|
|
55
|
+
/** Result of the synchronous bootstrap phase. */
|
|
56
|
+
readonly bootstrapResult: BootstrapResult;
|
|
57
|
+
/** Serialize `doc` and push to `Y.Text` using minimal diff. */
|
|
58
|
+
syncToSharedText(doc: Node): ReplaceTextResult;
|
|
59
|
+
/** Returns `true` if the transaction originated from `y-prosemirror` sync. */
|
|
60
|
+
isYjsSyncChange(tr: Transaction): boolean;
|
|
61
|
+
/** Remove the Y.Text observer. Call when tearing down. */
|
|
62
|
+
dispose(): void;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** Result of {@link replaceSharedText}. */
|
|
66
|
+
type ReplaceTextResult = {
|
|
67
|
+
ok: true;
|
|
68
|
+
} | {
|
|
69
|
+
ok: false;
|
|
70
|
+
reason: 'unchanged';
|
|
71
|
+
} | {
|
|
72
|
+
ok: false;
|
|
73
|
+
reason: 'detached';
|
|
74
|
+
};
|
|
75
|
+
/** Result of {@link replaceSharedProseMirror}. */
|
|
76
|
+
type ReplaceProseMirrorResult = {
|
|
77
|
+
ok: true;
|
|
78
|
+
} | {
|
|
79
|
+
ok: false;
|
|
80
|
+
reason: 'parse-error';
|
|
81
|
+
} | {
|
|
82
|
+
ok: false;
|
|
83
|
+
reason: 'detached';
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Union of all replace-result types. Kept for backward compatibility.
|
|
87
|
+
* Prefer the narrower {@link ReplaceTextResult} / {@link ReplaceProseMirrorResult}.
|
|
88
|
+
*/
|
|
89
|
+
type ReplaceResult = ReplaceTextResult | ReplaceProseMirrorResult;
|
|
90
|
+
/**
|
|
91
|
+
* Replace `Y.Text` content using a minimal diff (common prefix/suffix trimming).
|
|
92
|
+
* Returns a {@link ReplaceResult} indicating success or failure reason.
|
|
93
|
+
*/
|
|
94
|
+
declare function replaceSharedText(sharedText: Text, next: string, origin: unknown, normalize?: Normalize): ReplaceTextResult;
|
|
95
|
+
/**
|
|
96
|
+
* Replace `Y.XmlFragment` by parsing serialized text into a ProseMirror document.
|
|
97
|
+
* Returns a {@link ReplaceResult} indicating success or failure reason.
|
|
98
|
+
*/
|
|
99
|
+
declare function replaceSharedProseMirror(doc: Doc, fragment: XmlFragment, text: string, origin: unknown, config: Pick<YjsBridgeConfig, 'schema' | 'parse' | 'normalize' | 'onError'>): ReplaceProseMirrorResult;
|
|
100
|
+
/** Options for {@link createYjsBridge}. */
|
|
101
|
+
type YjsBridgeOptions = {
|
|
102
|
+
initialText?: string;
|
|
103
|
+
/** Which side wins when both sharedText and sharedProseMirror exist and differ. Default `'text'`. */
|
|
104
|
+
prefer?: 'text' | 'prosemirror';
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* Create a collaborative bridge that keeps `Y.Text` and `Y.XmlFragment` in sync.
|
|
108
|
+
*
|
|
109
|
+
* Runs a synchronous bootstrap to reconcile existing state, then installs a
|
|
110
|
+
* `Y.Text` observer for the text → ProseMirror direction.
|
|
111
|
+
*
|
|
112
|
+
* @throws If `sharedText` or `sharedProseMirror` belong to a different `Y.Doc`.
|
|
113
|
+
*/
|
|
114
|
+
declare function createYjsBridge(config: YjsBridgeConfig, options?: YjsBridgeOptions): YjsBridgeHandle;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Create a Proxy around a Yjs {@link Awareness} that suppresses the specified
|
|
118
|
+
* cursor field. This prevents y-prosemirror's built-in cursor management from
|
|
119
|
+
* conflicting with the PM↔CM cursor sync plugin.
|
|
120
|
+
*
|
|
121
|
+
* Other `setLocalStateField` calls are passed through unchanged.
|
|
122
|
+
*/
|
|
123
|
+
declare function createAwarenessProxy(awareness: Awareness, cursorField?: string): Awareness;
|
|
124
|
+
|
|
125
|
+
/** Yjs ↔ ProseMirror node mapping used by `y-prosemirror`. */
|
|
126
|
+
type ProseMirrorMapping = Map<AbstractType<unknown>, Node | Node[]>;
|
|
127
|
+
/** Options forwarded to `yCursorPlugin` from y-prosemirror. */
|
|
128
|
+
type YCursorPluginOpts = {
|
|
129
|
+
awarenessStateFilter?: (currentClientId: number, userClientId: number, user: unknown) => boolean;
|
|
130
|
+
cursorBuilder?: (user: unknown, clientId: number) => HTMLElement;
|
|
131
|
+
selectionBuilder?: (user: unknown, clientId: number) => DecorationAttrs;
|
|
132
|
+
getSelection?: (state: EditorState) => unknown;
|
|
133
|
+
};
|
|
134
|
+
/** Options forwarded to `yUndoPlugin` from y-prosemirror. */
|
|
135
|
+
type YUndoPluginOpts = {
|
|
136
|
+
protectedNodes?: Set<string>;
|
|
137
|
+
trackedOrigins?: unknown[];
|
|
138
|
+
undoManager?: UndoManager | null;
|
|
139
|
+
};
|
|
140
|
+
/** Options for {@link createCollabPlugins}. */
|
|
141
|
+
type CollabPluginsOptions = {
|
|
142
|
+
/** Shared ProseMirror document in Yjs. */
|
|
143
|
+
sharedProseMirror: XmlFragment;
|
|
144
|
+
awareness: Awareness;
|
|
145
|
+
cursorFieldName?: string;
|
|
146
|
+
serialize?: Serialize;
|
|
147
|
+
/** Awareness field used for CM/Y.Text cursor payloads. Default `'cursor'`. */
|
|
148
|
+
cmCursorFieldName?: string;
|
|
149
|
+
locate?: LocateText;
|
|
150
|
+
/**
|
|
151
|
+
* Enable PM↔CM cursor sync. Default `false`.
|
|
152
|
+
*
|
|
153
|
+
* When enabled, an {@link createAwarenessProxy | awareness proxy} is applied
|
|
154
|
+
* to suppress y-prosemirror's built-in cursor management.
|
|
155
|
+
*/
|
|
156
|
+
cursorSync?: boolean;
|
|
157
|
+
/**
|
|
158
|
+
* The shared `Y.Text` instance. When provided, the cursor sync plugin also
|
|
159
|
+
* broadcasts CM-format cursor positions so remote `yCollab` instances render them.
|
|
160
|
+
*/
|
|
161
|
+
sharedText?: Text;
|
|
162
|
+
/**
|
|
163
|
+
* When provided, a bridge sync plugin is inserted before the cursor sync plugin
|
|
164
|
+
* to ensure Y.Text is synced before cursor positions are computed. This guarantees
|
|
165
|
+
* that serialize-based offsets match Y.Text indices.
|
|
166
|
+
*/
|
|
167
|
+
bridge?: YjsBridgeHandle;
|
|
168
|
+
/** Extra options forwarded to `yCursorPlugin`. */
|
|
169
|
+
yCursorPluginOpts?: YCursorPluginOpts;
|
|
170
|
+
/** Extra options forwarded to `yUndoPlugin`. */
|
|
171
|
+
yUndoPluginOpts?: YUndoPluginOpts;
|
|
172
|
+
/** Called for non-fatal warnings. Propagated to child plugins. Default `console.warn`. */
|
|
173
|
+
onWarning?: OnWarning;
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* Bundle `ySyncPlugin`, `yCursorPlugin`, `yUndoPlugin` from y-prosemirror,
|
|
177
|
+
* plus an optional PM↔CM cursor sync plugin.
|
|
178
|
+
*
|
|
179
|
+
* @throws If `cursorSync: true` but `serialize` is not provided.
|
|
180
|
+
*/
|
|
181
|
+
declare function createCollabPlugins(schema: Schema, options: CollabPluginsOptions): {
|
|
182
|
+
plugins: Plugin[];
|
|
183
|
+
doc: Node;
|
|
184
|
+
mapping: ProseMirrorMapping;
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
type BridgeSyncState = {
|
|
188
|
+
needsSync: boolean;
|
|
189
|
+
};
|
|
190
|
+
type BridgeSyncFailure = {
|
|
191
|
+
ok: false;
|
|
192
|
+
reason: 'detached';
|
|
193
|
+
};
|
|
194
|
+
/** Options for {@link createBridgeSyncPlugin}. */
|
|
195
|
+
type BridgeSyncPluginOptions = {
|
|
196
|
+
/** Called when `syncToSharedText` fails (excludes `reason: 'unchanged'`). */
|
|
197
|
+
onSyncFailure?: (result: BridgeSyncFailure, view: EditorView) => void;
|
|
198
|
+
/** Called for non-fatal warnings. Default `console.warn`. */
|
|
199
|
+
onWarning?: OnWarning;
|
|
200
|
+
};
|
|
201
|
+
/** ProseMirror plugin key for {@link createBridgeSyncPlugin}. Use to read the plugin state. */
|
|
202
|
+
declare const bridgeSyncPluginKey: PluginKey<BridgeSyncState>;
|
|
203
|
+
/**
|
|
204
|
+
* ProseMirror plugin that automatically syncs PM doc changes to Y.Text
|
|
205
|
+
* via the bridge handle. Skips Yjs-originated changes to avoid loops.
|
|
206
|
+
*
|
|
207
|
+
* A warning is logged if the same bridge handle is wired more than once.
|
|
208
|
+
* The guard is cleaned up when the plugin is destroyed.
|
|
209
|
+
*/
|
|
210
|
+
declare function createBridgeSyncPlugin(bridge: YjsBridgeHandle, options?: BridgeSyncPluginOptions): Plugin;
|
|
211
|
+
|
|
212
|
+
/** Plugin state for the cursor sync plugin. Read via {@link cursorSyncPluginKey}. */
|
|
213
|
+
type CursorSyncState = {
|
|
214
|
+
/** Pending CodeMirror cursor to broadcast. Set by {@link syncCmCursor}. */
|
|
215
|
+
pendingCm: {
|
|
216
|
+
anchor: number;
|
|
217
|
+
head: number;
|
|
218
|
+
} | null;
|
|
219
|
+
/** Text offset mapped from the current PM selection anchor. `null` when no mapping is available. */
|
|
220
|
+
mappedTextOffset: number | null;
|
|
221
|
+
};
|
|
222
|
+
/** ProseMirror plugin key for {@link createCursorSyncPlugin}. Use to read the plugin state. */
|
|
223
|
+
declare const cursorSyncPluginKey: PluginKey<CursorSyncState>;
|
|
224
|
+
/** Options for {@link createCursorSyncPlugin}. */
|
|
225
|
+
type CursorSyncPluginOptions = {
|
|
226
|
+
awareness: Awareness;
|
|
227
|
+
serialize: Serialize;
|
|
228
|
+
cursorFieldName?: string;
|
|
229
|
+
/** Awareness field used for CM/Y.Text cursor payloads. Default `'cursor'`. */
|
|
230
|
+
cmCursorFieldName?: string;
|
|
231
|
+
locate?: LocateText;
|
|
232
|
+
/**
|
|
233
|
+
* When provided, the plugin also broadcasts CM-format cursor positions
|
|
234
|
+
* (Y.Text relative positions) to the awareness field specified by
|
|
235
|
+
* `cmCursorFieldName`, so that remote `yCollab` instances can render the cursor.
|
|
236
|
+
*/
|
|
237
|
+
sharedText?: Text;
|
|
238
|
+
/** Called for non-fatal warnings. Default `console.warn`. */
|
|
239
|
+
onWarning?: OnWarning;
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* ProseMirror plugin that synchronizes cursor positions between PM and CM via Yjs awareness.
|
|
243
|
+
*
|
|
244
|
+
* - PM → awareness: automatically broadcasts when the PM view is focused and selection changes.
|
|
245
|
+
* - CM → awareness: triggered by dispatching {@link syncCmCursor}.
|
|
246
|
+
*/
|
|
247
|
+
declare function createCursorSyncPlugin(options: CursorSyncPluginOptions): Plugin;
|
|
248
|
+
/**
|
|
249
|
+
* Dispatch a CodeMirror cursor offset (or range) to the cursor sync plugin.
|
|
250
|
+
* The plugin will convert it to a ProseMirror position and broadcast via awareness.
|
|
251
|
+
*
|
|
252
|
+
* @param view - The ProseMirror EditorView that has the cursor sync plugin installed.
|
|
253
|
+
* @param anchor - CodeMirror text offset for the anchor.
|
|
254
|
+
* @param head - CodeMirror text offset for the head (defaults to `anchor` for a collapsed cursor).
|
|
255
|
+
* @param onWarning - Optional warning callback. Default `console.warn`.
|
|
256
|
+
*/
|
|
257
|
+
declare function syncCmCursor(view: EditorView, anchor: number, head?: number, onWarning?: OnWarning): void;
|
|
258
|
+
|
|
259
|
+
export { type BootstrapResult, type BridgeSyncPluginOptions, type CollabPluginsOptions, type CursorSyncPluginOptions, type CursorSyncState, ORIGIN_INIT, ORIGIN_PM_TO_TEXT, ORIGIN_TEXT_TO_PM, type OnWarning, type ProseMirrorMapping, type ReplaceProseMirrorResult, type ReplaceResult, type ReplaceTextResult, type WarningCode, type WarningEvent, type YCursorPluginOpts, type YUndoPluginOpts, type YjsBridgeConfig, type YjsBridgeHandle, type YjsBridgeOptions, bridgeSyncPluginKey, createAwarenessProxy, createBridgeSyncPlugin, createCollabPlugins, createCursorSyncPlugin, createYjsBridge, cursorSyncPluginKey, replaceSharedProseMirror, replaceSharedText, syncCmCursor };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { Doc, Text, XmlFragment, UndoManager, AbstractType } from 'yjs';
|
|
2
|
+
import { Serialize, Parse, Normalize, OnError, LocateText } from '@pm-cm/core';
|
|
3
|
+
export { CursorMap, ErrorCode, ErrorEvent, LocateText, Normalize, OnError, Parse, Serialize, TextSegment, buildCursorMap, cursorMapLookup, reverseCursorMapLookup } from '@pm-cm/core';
|
|
4
|
+
import { Node, Schema } from 'prosemirror-model';
|
|
5
|
+
import { Transaction, EditorState, Plugin, PluginKey } from 'prosemirror-state';
|
|
6
|
+
import { Awareness } from 'y-protocols/awareness';
|
|
7
|
+
import { DecorationAttrs, EditorView } from 'prosemirror-view';
|
|
8
|
+
|
|
9
|
+
/** Known warning codes emitted by the yjs bridge and plugins. */
|
|
10
|
+
type WarningCode = 'bridge-already-wired' | 'sync-failed' | 'ysync-plugin-missing' | 'cursor-sync-not-installed';
|
|
11
|
+
/** Structured warning event for non-fatal warnings. */
|
|
12
|
+
type WarningEvent = {
|
|
13
|
+
code: WarningCode;
|
|
14
|
+
message: string;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Warning handler callback for non-fatal warnings.
|
|
18
|
+
*
|
|
19
|
+
* Known codes:
|
|
20
|
+
* - `'bridge-already-wired'` — the same bridge handle is wired to multiple plugin instances.
|
|
21
|
+
* - `'sync-failed'` — `syncToSharedText` failed (e.g. Y.Text detached).
|
|
22
|
+
* - `'ysync-plugin-missing'` — ySyncPlugin state is not available; cursor broadcast skipped.
|
|
23
|
+
* - `'cursor-sync-not-installed'` — cursor sync plugin is not installed on the EditorView.
|
|
24
|
+
*/
|
|
25
|
+
type OnWarning = (event: WarningEvent) => void;
|
|
26
|
+
/** Yjs transaction origin: text → ProseMirror direction. */
|
|
27
|
+
declare const ORIGIN_TEXT_TO_PM = "bridge:text-to-prosemirror";
|
|
28
|
+
/** Yjs transaction origin: ProseMirror → text direction. */
|
|
29
|
+
declare const ORIGIN_PM_TO_TEXT = "bridge:prosemirror-to-text";
|
|
30
|
+
/** Yjs transaction origin: bootstrap initialization. */
|
|
31
|
+
declare const ORIGIN_INIT = "bridge:init";
|
|
32
|
+
/** Configuration for {@link createYjsBridge}. */
|
|
33
|
+
type YjsBridgeConfig = {
|
|
34
|
+
doc: Doc;
|
|
35
|
+
sharedText: Text;
|
|
36
|
+
sharedProseMirror: XmlFragment;
|
|
37
|
+
schema: Schema;
|
|
38
|
+
serialize: Serialize;
|
|
39
|
+
parse: Parse;
|
|
40
|
+
normalize?: Normalize;
|
|
41
|
+
/** Called on non-fatal errors (e.g. parse failures). Defaults to `console.error`. */
|
|
42
|
+
onError?: OnError;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Result of the bootstrap phase in {@link createYjsBridge}.
|
|
46
|
+
* Indicates which source was used to initialize the shared types.
|
|
47
|
+
*/
|
|
48
|
+
type BootstrapResult = {
|
|
49
|
+
source: 'text' | 'prosemirror' | 'both-match' | 'empty' | 'initial';
|
|
50
|
+
/** `true` when format conversion (parse or serialize) failed during bootstrap. The bridge is still usable but the affected shared type may be stale. */
|
|
51
|
+
parseError?: boolean;
|
|
52
|
+
};
|
|
53
|
+
/** Handle returned by {@link createYjsBridge}. */
|
|
54
|
+
type YjsBridgeHandle = {
|
|
55
|
+
/** Result of the synchronous bootstrap phase. */
|
|
56
|
+
readonly bootstrapResult: BootstrapResult;
|
|
57
|
+
/** Serialize `doc` and push to `Y.Text` using minimal diff. */
|
|
58
|
+
syncToSharedText(doc: Node): ReplaceTextResult;
|
|
59
|
+
/** Returns `true` if the transaction originated from `y-prosemirror` sync. */
|
|
60
|
+
isYjsSyncChange(tr: Transaction): boolean;
|
|
61
|
+
/** Remove the Y.Text observer. Call when tearing down. */
|
|
62
|
+
dispose(): void;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** Result of {@link replaceSharedText}. */
|
|
66
|
+
type ReplaceTextResult = {
|
|
67
|
+
ok: true;
|
|
68
|
+
} | {
|
|
69
|
+
ok: false;
|
|
70
|
+
reason: 'unchanged';
|
|
71
|
+
} | {
|
|
72
|
+
ok: false;
|
|
73
|
+
reason: 'detached';
|
|
74
|
+
};
|
|
75
|
+
/** Result of {@link replaceSharedProseMirror}. */
|
|
76
|
+
type ReplaceProseMirrorResult = {
|
|
77
|
+
ok: true;
|
|
78
|
+
} | {
|
|
79
|
+
ok: false;
|
|
80
|
+
reason: 'parse-error';
|
|
81
|
+
} | {
|
|
82
|
+
ok: false;
|
|
83
|
+
reason: 'detached';
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Union of all replace-result types. Kept for backward compatibility.
|
|
87
|
+
* Prefer the narrower {@link ReplaceTextResult} / {@link ReplaceProseMirrorResult}.
|
|
88
|
+
*/
|
|
89
|
+
type ReplaceResult = ReplaceTextResult | ReplaceProseMirrorResult;
|
|
90
|
+
/**
|
|
91
|
+
* Replace `Y.Text` content using a minimal diff (common prefix/suffix trimming).
|
|
92
|
+
* Returns a {@link ReplaceResult} indicating success or failure reason.
|
|
93
|
+
*/
|
|
94
|
+
declare function replaceSharedText(sharedText: Text, next: string, origin: unknown, normalize?: Normalize): ReplaceTextResult;
|
|
95
|
+
/**
|
|
96
|
+
* Replace `Y.XmlFragment` by parsing serialized text into a ProseMirror document.
|
|
97
|
+
* Returns a {@link ReplaceResult} indicating success or failure reason.
|
|
98
|
+
*/
|
|
99
|
+
declare function replaceSharedProseMirror(doc: Doc, fragment: XmlFragment, text: string, origin: unknown, config: Pick<YjsBridgeConfig, 'schema' | 'parse' | 'normalize' | 'onError'>): ReplaceProseMirrorResult;
|
|
100
|
+
/** Options for {@link createYjsBridge}. */
|
|
101
|
+
type YjsBridgeOptions = {
|
|
102
|
+
initialText?: string;
|
|
103
|
+
/** Which side wins when both sharedText and sharedProseMirror exist and differ. Default `'text'`. */
|
|
104
|
+
prefer?: 'text' | 'prosemirror';
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* Create a collaborative bridge that keeps `Y.Text` and `Y.XmlFragment` in sync.
|
|
108
|
+
*
|
|
109
|
+
* Runs a synchronous bootstrap to reconcile existing state, then installs a
|
|
110
|
+
* `Y.Text` observer for the text → ProseMirror direction.
|
|
111
|
+
*
|
|
112
|
+
* @throws If `sharedText` or `sharedProseMirror` belong to a different `Y.Doc`.
|
|
113
|
+
*/
|
|
114
|
+
declare function createYjsBridge(config: YjsBridgeConfig, options?: YjsBridgeOptions): YjsBridgeHandle;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Create a Proxy around a Yjs {@link Awareness} that suppresses the specified
|
|
118
|
+
* cursor field. This prevents y-prosemirror's built-in cursor management from
|
|
119
|
+
* conflicting with the PM↔CM cursor sync plugin.
|
|
120
|
+
*
|
|
121
|
+
* Other `setLocalStateField` calls are passed through unchanged.
|
|
122
|
+
*/
|
|
123
|
+
declare function createAwarenessProxy(awareness: Awareness, cursorField?: string): Awareness;
|
|
124
|
+
|
|
125
|
+
/** Yjs ↔ ProseMirror node mapping used by `y-prosemirror`. */
|
|
126
|
+
type ProseMirrorMapping = Map<AbstractType<unknown>, Node | Node[]>;
|
|
127
|
+
/** Options forwarded to `yCursorPlugin` from y-prosemirror. */
|
|
128
|
+
type YCursorPluginOpts = {
|
|
129
|
+
awarenessStateFilter?: (currentClientId: number, userClientId: number, user: unknown) => boolean;
|
|
130
|
+
cursorBuilder?: (user: unknown, clientId: number) => HTMLElement;
|
|
131
|
+
selectionBuilder?: (user: unknown, clientId: number) => DecorationAttrs;
|
|
132
|
+
getSelection?: (state: EditorState) => unknown;
|
|
133
|
+
};
|
|
134
|
+
/** Options forwarded to `yUndoPlugin` from y-prosemirror. */
|
|
135
|
+
type YUndoPluginOpts = {
|
|
136
|
+
protectedNodes?: Set<string>;
|
|
137
|
+
trackedOrigins?: unknown[];
|
|
138
|
+
undoManager?: UndoManager | null;
|
|
139
|
+
};
|
|
140
|
+
/** Options for {@link createCollabPlugins}. */
|
|
141
|
+
type CollabPluginsOptions = {
|
|
142
|
+
/** Shared ProseMirror document in Yjs. */
|
|
143
|
+
sharedProseMirror: XmlFragment;
|
|
144
|
+
awareness: Awareness;
|
|
145
|
+
cursorFieldName?: string;
|
|
146
|
+
serialize?: Serialize;
|
|
147
|
+
/** Awareness field used for CM/Y.Text cursor payloads. Default `'cursor'`. */
|
|
148
|
+
cmCursorFieldName?: string;
|
|
149
|
+
locate?: LocateText;
|
|
150
|
+
/**
|
|
151
|
+
* Enable PM↔CM cursor sync. Default `false`.
|
|
152
|
+
*
|
|
153
|
+
* When enabled, an {@link createAwarenessProxy | awareness proxy} is applied
|
|
154
|
+
* to suppress y-prosemirror's built-in cursor management.
|
|
155
|
+
*/
|
|
156
|
+
cursorSync?: boolean;
|
|
157
|
+
/**
|
|
158
|
+
* The shared `Y.Text` instance. When provided, the cursor sync plugin also
|
|
159
|
+
* broadcasts CM-format cursor positions so remote `yCollab` instances render them.
|
|
160
|
+
*/
|
|
161
|
+
sharedText?: Text;
|
|
162
|
+
/**
|
|
163
|
+
* When provided, a bridge sync plugin is inserted before the cursor sync plugin
|
|
164
|
+
* to ensure Y.Text is synced before cursor positions are computed. This guarantees
|
|
165
|
+
* that serialize-based offsets match Y.Text indices.
|
|
166
|
+
*/
|
|
167
|
+
bridge?: YjsBridgeHandle;
|
|
168
|
+
/** Extra options forwarded to `yCursorPlugin`. */
|
|
169
|
+
yCursorPluginOpts?: YCursorPluginOpts;
|
|
170
|
+
/** Extra options forwarded to `yUndoPlugin`. */
|
|
171
|
+
yUndoPluginOpts?: YUndoPluginOpts;
|
|
172
|
+
/** Called for non-fatal warnings. Propagated to child plugins. Default `console.warn`. */
|
|
173
|
+
onWarning?: OnWarning;
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* Bundle `ySyncPlugin`, `yCursorPlugin`, `yUndoPlugin` from y-prosemirror,
|
|
177
|
+
* plus an optional PM↔CM cursor sync plugin.
|
|
178
|
+
*
|
|
179
|
+
* @throws If `cursorSync: true` but `serialize` is not provided.
|
|
180
|
+
*/
|
|
181
|
+
declare function createCollabPlugins(schema: Schema, options: CollabPluginsOptions): {
|
|
182
|
+
plugins: Plugin[];
|
|
183
|
+
doc: Node;
|
|
184
|
+
mapping: ProseMirrorMapping;
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
type BridgeSyncState = {
|
|
188
|
+
needsSync: boolean;
|
|
189
|
+
};
|
|
190
|
+
type BridgeSyncFailure = {
|
|
191
|
+
ok: false;
|
|
192
|
+
reason: 'detached';
|
|
193
|
+
};
|
|
194
|
+
/** Options for {@link createBridgeSyncPlugin}. */
|
|
195
|
+
type BridgeSyncPluginOptions = {
|
|
196
|
+
/** Called when `syncToSharedText` fails (excludes `reason: 'unchanged'`). */
|
|
197
|
+
onSyncFailure?: (result: BridgeSyncFailure, view: EditorView) => void;
|
|
198
|
+
/** Called for non-fatal warnings. Default `console.warn`. */
|
|
199
|
+
onWarning?: OnWarning;
|
|
200
|
+
};
|
|
201
|
+
/** ProseMirror plugin key for {@link createBridgeSyncPlugin}. Use to read the plugin state. */
|
|
202
|
+
declare const bridgeSyncPluginKey: PluginKey<BridgeSyncState>;
|
|
203
|
+
/**
|
|
204
|
+
* ProseMirror plugin that automatically syncs PM doc changes to Y.Text
|
|
205
|
+
* via the bridge handle. Skips Yjs-originated changes to avoid loops.
|
|
206
|
+
*
|
|
207
|
+
* A warning is logged if the same bridge handle is wired more than once.
|
|
208
|
+
* The guard is cleaned up when the plugin is destroyed.
|
|
209
|
+
*/
|
|
210
|
+
declare function createBridgeSyncPlugin(bridge: YjsBridgeHandle, options?: BridgeSyncPluginOptions): Plugin;
|
|
211
|
+
|
|
212
|
+
/** Plugin state for the cursor sync plugin. Read via {@link cursorSyncPluginKey}. */
|
|
213
|
+
type CursorSyncState = {
|
|
214
|
+
/** Pending CodeMirror cursor to broadcast. Set by {@link syncCmCursor}. */
|
|
215
|
+
pendingCm: {
|
|
216
|
+
anchor: number;
|
|
217
|
+
head: number;
|
|
218
|
+
} | null;
|
|
219
|
+
/** Text offset mapped from the current PM selection anchor. `null` when no mapping is available. */
|
|
220
|
+
mappedTextOffset: number | null;
|
|
221
|
+
};
|
|
222
|
+
/** ProseMirror plugin key for {@link createCursorSyncPlugin}. Use to read the plugin state. */
|
|
223
|
+
declare const cursorSyncPluginKey: PluginKey<CursorSyncState>;
|
|
224
|
+
/** Options for {@link createCursorSyncPlugin}. */
|
|
225
|
+
type CursorSyncPluginOptions = {
|
|
226
|
+
awareness: Awareness;
|
|
227
|
+
serialize: Serialize;
|
|
228
|
+
cursorFieldName?: string;
|
|
229
|
+
/** Awareness field used for CM/Y.Text cursor payloads. Default `'cursor'`. */
|
|
230
|
+
cmCursorFieldName?: string;
|
|
231
|
+
locate?: LocateText;
|
|
232
|
+
/**
|
|
233
|
+
* When provided, the plugin also broadcasts CM-format cursor positions
|
|
234
|
+
* (Y.Text relative positions) to the awareness field specified by
|
|
235
|
+
* `cmCursorFieldName`, so that remote `yCollab` instances can render the cursor.
|
|
236
|
+
*/
|
|
237
|
+
sharedText?: Text;
|
|
238
|
+
/** Called for non-fatal warnings. Default `console.warn`. */
|
|
239
|
+
onWarning?: OnWarning;
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* ProseMirror plugin that synchronizes cursor positions between PM and CM via Yjs awareness.
|
|
243
|
+
*
|
|
244
|
+
* - PM → awareness: automatically broadcasts when the PM view is focused and selection changes.
|
|
245
|
+
* - CM → awareness: triggered by dispatching {@link syncCmCursor}.
|
|
246
|
+
*/
|
|
247
|
+
declare function createCursorSyncPlugin(options: CursorSyncPluginOptions): Plugin;
|
|
248
|
+
/**
|
|
249
|
+
* Dispatch a CodeMirror cursor offset (or range) to the cursor sync plugin.
|
|
250
|
+
* The plugin will convert it to a ProseMirror position and broadcast via awareness.
|
|
251
|
+
*
|
|
252
|
+
* @param view - The ProseMirror EditorView that has the cursor sync plugin installed.
|
|
253
|
+
* @param anchor - CodeMirror text offset for the anchor.
|
|
254
|
+
* @param head - CodeMirror text offset for the head (defaults to `anchor` for a collapsed cursor).
|
|
255
|
+
* @param onWarning - Optional warning callback. Default `console.warn`.
|
|
256
|
+
*/
|
|
257
|
+
declare function syncCmCursor(view: EditorView, anchor: number, head?: number, onWarning?: OnWarning): void;
|
|
258
|
+
|
|
259
|
+
export { type BootstrapResult, type BridgeSyncPluginOptions, type CollabPluginsOptions, type CursorSyncPluginOptions, type CursorSyncState, ORIGIN_INIT, ORIGIN_PM_TO_TEXT, ORIGIN_TEXT_TO_PM, type OnWarning, type ProseMirrorMapping, type ReplaceProseMirrorResult, type ReplaceResult, type ReplaceTextResult, type WarningCode, type WarningEvent, type YCursorPluginOpts, type YUndoPluginOpts, type YjsBridgeConfig, type YjsBridgeHandle, type YjsBridgeOptions, bridgeSyncPluginKey, createAwarenessProxy, createBridgeSyncPlugin, createCollabPlugins, createCursorSyncPlugin, createYjsBridge, cursorSyncPluginKey, replaceSharedProseMirror, replaceSharedText, syncCmCursor };
|