@pilotiq/tiptap 3.1.1 → 3.2.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.
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Plain-text editor factory — Tiptap editor config tuned to behave like a
3
+ * native `<input>` (single-line) or `<textarea>` (multi-line), with no marks
4
+ * and a Document schema restricted to paragraph(s) of inline text.
5
+ *
6
+ * Built for `@pilotiq/pilotiq`'s collab-text-field path: when collab is on,
7
+ * the renderer mounts a Tiptap editor instead of a native input so y-prosemirror
8
+ * can anchor selections to Yjs `RelativePosition` items (positional identity).
9
+ * This avoids the cursor-jump + concurrent-insert races inherent to the
10
+ * `Y.Text` + manual `computeDelta` + heuristic `preserveCursor` path.
11
+ *
12
+ * Pure config — no React. Caller passes the returned object to `useEditor` or
13
+ * `new Editor(...)`. Caller is also responsible for passing in the collab
14
+ * extension list (typically `Collaboration` + `CollaborationCursor` from the
15
+ * pilotiq collab adapter); we never import `@tiptap/extension-collaboration`
16
+ * directly so the open-core package stays free of collab peer deps.
17
+ */
18
+ import {
19
+ Node,
20
+ Extension,
21
+ mergeAttributes,
22
+ type AnyExtension,
23
+ type EditorOptions,
24
+ type Editor,
25
+ } from '@tiptap/core'
26
+ import Placeholder from '@tiptap/extension-placeholder'
27
+
28
+ /** Block separator used by `getText` — newline matches `<textarea>.value`. */
29
+ const BLOCK_SEPARATOR = '\n'
30
+
31
+ /**
32
+ * Bare paragraph block — the only block the plain-text schema permits.
33
+ * No options, no input rules, no toggles. `inline*` content lets any inline
34
+ * node (today just `text`) appear inside.
35
+ */
36
+ const PlainTextParagraph = Node.create({
37
+ name: 'paragraph',
38
+ group: 'block',
39
+ content: 'inline*',
40
+ priority: 1000,
41
+ parseHTML() {
42
+ return [{ tag: 'p' }]
43
+ },
44
+ renderHTML({ HTMLAttributes }) {
45
+ return ['p', mergeAttributes(HTMLAttributes), 0]
46
+ },
47
+ })
48
+
49
+ /** The text node — Tiptap requires this to be defined explicitly. */
50
+ const PlainTextText = Node.create({
51
+ name: 'text',
52
+ group: 'inline',
53
+ })
54
+
55
+ /**
56
+ * Build a Document node with content restricted to either a single paragraph
57
+ * (single-line mode) or one-or-more paragraphs (multi-line mode). The schema
58
+ * itself blocks paste of incompatible content — ProseMirror will coerce or
59
+ * reject non-matching nodes at parse time.
60
+ */
61
+ function makePlainTextDocument(multiline: boolean) {
62
+ return Node.create({
63
+ name: 'doc',
64
+ topNode: true,
65
+ content: multiline ? 'paragraph+' : 'paragraph',
66
+ })
67
+ }
68
+
69
+ /**
70
+ * Single-line Enter handler. Tiptap's default `Enter` keymap splits the
71
+ * paragraph — meaningless when the schema only allows exactly one — so we
72
+ * intercept and either delegate to `onSubmit` (caller-supplied) or blur.
73
+ *
74
+ * Filament's plain-text fields blur on Enter; matching that default.
75
+ */
76
+ function makeSingleLineKeymap(onSubmit: ((editor: Editor) => boolean | void) | undefined) {
77
+ return Extension.create({
78
+ name: 'plainTextSingleLineKeymap',
79
+ addKeyboardShortcuts() {
80
+ const handleEnter = (): boolean => {
81
+ const handled = onSubmit?.(this.editor)
82
+ if (handled === true) return true
83
+ this.editor.commands.blur()
84
+ return true
85
+ }
86
+ return {
87
+ Enter: handleEnter,
88
+ 'Mod-Enter': () => true,
89
+ 'Shift-Enter': () => true,
90
+ }
91
+ },
92
+ })
93
+ }
94
+
95
+ export interface PlainTextEditorOptions {
96
+ /** If true, allow multiple paragraphs (textarea-like). Default `false` (input-like). */
97
+ multiline?: boolean
98
+ /** Placeholder text shown while the editor is empty. */
99
+ placeholder?: string
100
+ /** Editable / disabled state. Default `true`. */
101
+ editable?: boolean
102
+ /**
103
+ * Initial textual content. Ignored when a Collaboration extension is passed
104
+ * via `extensions` — Collaboration takes ownership of the document and seeds
105
+ * from the Yjs fragment instead. Use the caller's own first-load seed (see
106
+ * `@pilotiq/tiptap` README) when collab is on.
107
+ */
108
+ content?: string
109
+ /**
110
+ * Extra extensions to merge into the editor — typically the Collaboration +
111
+ * CollaborationCursor pair from the pilotiq collab adapter. Pass `[]` (or
112
+ * omit) for the non-collab path.
113
+ */
114
+ extensions?: AnyExtension[]
115
+ /**
116
+ * Called on every editor update with the editor's plain-text value (blocks
117
+ * joined by `'\n'`). Use this to mirror the value into form-state for
118
+ * submission via a hidden `<input>`.
119
+ */
120
+ onUpdate?: (text: string, editor: Editor) => void
121
+ /**
122
+ * Single-line Enter handler. Return `true` to suppress the default blur
123
+ * behavior. When omitted, Enter simply blurs the editor.
124
+ */
125
+ onSubmit?: (editor: Editor) => boolean | void
126
+ /**
127
+ * DOM attributes for the editor's contenteditable wrapper — typically
128
+ * `{ class: '…tailwind classes…' }` to style the editor like the native
129
+ * `<input>` / `<textarea>` it replaces.
130
+ */
131
+ editorAttributes?: Record<string, string>
132
+ }
133
+
134
+ /**
135
+ * Read the editor's current value as plain text, with paragraphs joined by
136
+ * `'\n'`. Mirrors the behavior of `<textarea>.value`.
137
+ */
138
+ export function plainTextOf(editor: Editor): string {
139
+ return editor.getText({ blockSeparator: BLOCK_SEPARATOR })
140
+ }
141
+
142
+ /**
143
+ * Convert a plain-text string into a Tiptap JSON doc that satisfies the
144
+ * plain-text schema. Multi-line input splits on `'\n'` into separate
145
+ * paragraphs; single-line strips any embedded newlines into a single run.
146
+ * Exported for tests — pure, no editor instance required.
147
+ */
148
+ export function plainTextToDoc(text: string, multiline: boolean): {
149
+ type: 'doc'
150
+ content: Array<{ type: 'paragraph'; content?: Array<{ type: 'text'; text: string }> }>
151
+ } {
152
+ if (!multiline) {
153
+ const flat = text.replace(/\r?\n/g, '')
154
+ return {
155
+ type: 'doc',
156
+ content: [
157
+ flat ? { type: 'paragraph', content: [{ type: 'text', text: flat }] }
158
+ : { type: 'paragraph' },
159
+ ],
160
+ }
161
+ }
162
+ const lines = text.split(/\r?\n/)
163
+ return {
164
+ type: 'doc',
165
+ content: lines.map((line) =>
166
+ line ? { type: 'paragraph', content: [{ type: 'text', text: line }] }
167
+ : { type: 'paragraph' },
168
+ ),
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Build the Tiptap editor config for a plain-text field. Pass the returned
174
+ * object to `useEditor` (React) or `new Editor(...)` (vanilla).
175
+ *
176
+ * The editor schema is deliberately minimal:
177
+ * - `doc` → `paragraph` (single-line) or `paragraph+` (multi-line)
178
+ * - `paragraph` → `inline*`
179
+ * - `text` (inline)
180
+ *
181
+ * No marks, no input rules, no list items, no code blocks — just text. Pasted
182
+ * rich content is stripped to plain text by ProseMirror's schema enforcement.
183
+ */
184
+ export function createPlainTextEditor(
185
+ options: PlainTextEditorOptions = {},
186
+ ): Partial<EditorOptions> {
187
+ const {
188
+ multiline = false,
189
+ placeholder,
190
+ editable = true,
191
+ content = '',
192
+ extensions = [],
193
+ onUpdate,
194
+ onSubmit,
195
+ editorAttributes,
196
+ } = options
197
+
198
+ const schema: AnyExtension[] = [
199
+ makePlainTextDocument(multiline),
200
+ PlainTextParagraph,
201
+ PlainTextText,
202
+ ]
203
+
204
+ const behavior: AnyExtension[] = []
205
+ if (!multiline) behavior.push(makeSingleLineKeymap(onSubmit))
206
+ if (placeholder !== undefined) {
207
+ behavior.push(Placeholder.configure({ placeholder }))
208
+ }
209
+
210
+ const allExtensions: AnyExtension[] = [...schema, ...behavior, ...extensions]
211
+
212
+ // When Collaboration owns the doc, an explicit `content` would race the
213
+ // Yjs sync. Caller is responsible for omitting `content` in that case; we
214
+ // pass it through verbatim either way.
215
+ const initialContent = content ? plainTextToDoc(content, multiline) : ''
216
+
217
+ const config: Partial<EditorOptions> = {
218
+ editable,
219
+ extensions: allExtensions,
220
+ content: initialContent,
221
+ }
222
+ if (onUpdate) {
223
+ config.onUpdate = ({ editor }) => onUpdate(plainTextOf(editor), editor)
224
+ }
225
+ if (editorAttributes) {
226
+ config.editorProps = { attributes: editorAttributes }
227
+ }
228
+ return config
229
+ }
package/src/index.ts CHANGED
@@ -17,6 +17,12 @@ export {
17
17
  type MentionProviderMeta,
18
18
  } from './MentionProvider.js'
19
19
  export { registerTiptap } from './register.js'
20
+ export {
21
+ createPlainTextEditor,
22
+ plainTextOf,
23
+ plainTextToDoc,
24
+ type PlainTextEditorOptions,
25
+ } from './PlainTextEditor.js'
20
26
  export { tiptap } from './plugin.js'
21
27
  export { TiptapEditor } from './react/TiptapEditor.js'
22
28
  export {
@@ -0,0 +1,165 @@
1
+ import { useEffect, useMemo, useState } from 'react'
2
+ import { useEditor, EditorContent, type Extension } from '@tiptap/react'
3
+ import type { AnyExtension } from '@tiptap/core'
4
+ import {
5
+ useCollabRoom,
6
+ getCollabExtensions,
7
+ type CollabTextRendererProps,
8
+ } from '@pilotiq/pilotiq/react'
9
+ import { createPlainTextEditor, plainTextOf, plainTextToDoc } from '../PlainTextEditor.js'
10
+
11
+ /**
12
+ * Tiptap-backed plain-text editor for pilotiq's `TextField` / `TextareaField`
13
+ * / similar single-line / multi-line text fields when collab is on.
14
+ *
15
+ * Lifts the cursor-bookkeeping burden off the field renderer: y-prosemirror
16
+ * anchors selections to `Yjs.RelativePosition` items, so concurrent and
17
+ * mid-word remote edits translate the local cursor correctly without any
18
+ * heuristic. Replaces the legacy `Y.Text` + `computeDelta` + `preserveCursor`
19
+ * path documented in `docs/plans/text-fields-tiptap-backed-collab.md`.
20
+ *
21
+ * Mount conditions (enforced upstream by `TextLikeInput`):
22
+ * - A `<RecordCollabRoom>` is mounted up-tree (`useCollabRoom() !== null`).
23
+ * - A collab extension factory was registered (`getCollabExtensions() !== null`).
24
+ * - The field hasn't opted out via `.collab(false)`.
25
+ * - The field is not masked (`.mask(pattern)`).
26
+ * - The field is top-level (not a Repeater / Builder row leaf).
27
+ *
28
+ * If either the room or the factory disappears at runtime (e.g. the plugin
29
+ * was never installed), we still render an editor — it's just a non-collab
30
+ * plain Tiptap. That's a regression vs `<input>` ergonomically but never
31
+ * crashes; in practice the upstream gate prevents this branch from mounting
32
+ * when collab isn't wired.
33
+ */
34
+ export function CollabTextRenderer({
35
+ name,
36
+ multiline,
37
+ defaultValue,
38
+ placeholder,
39
+ disabled,
40
+ onChange,
41
+ onBlur,
42
+ onSubmit,
43
+ className,
44
+ editorAttributes,
45
+ }: CollabTextRendererProps): React.ReactElement {
46
+ const room = useCollabRoom()
47
+ const factory = getCollabExtensions()
48
+ const collabActive = !!(room && factory)
49
+
50
+ // Built once per editor mount. The factory closes over the room's `ydoc`
51
+ // + `provider` and the field name to produce a `Collaboration` (and
52
+ // optional `CollaborationCursor`) extension targeting the field's
53
+ // `Y.XmlFragment`. Re-running on every render would tear down the editor.
54
+ const collabExtensions = useMemo<AnyExtension[]>(() => {
55
+ if (!collabActive || !room || !factory) return []
56
+ return factory({
57
+ ydoc: room.ydoc,
58
+ provider: room.provider,
59
+ fieldName: name,
60
+ ...(room.user ? { user: room.user } : {}),
61
+ }) as Extension[]
62
+ // eslint-disable-next-line react-hooks/exhaustive-deps
63
+ }, [collabActive])
64
+
65
+ const editor = useEditor(
66
+ createPlainTextEditor({
67
+ multiline,
68
+ ...(placeholder !== undefined ? { placeholder } : {}),
69
+ editable: !disabled,
70
+ // When Collaboration owns the doc, omit `content` so the editor
71
+ // doesn't race the y-prosemirror sync. The post-`synced` effect below
72
+ // seeds the fragment on first connect when it's still empty. When
73
+ // collab is off, seed from defaultValue directly.
74
+ content: collabActive ? '' : defaultValue,
75
+ extensions: collabExtensions,
76
+ onUpdate: (text) => onChange(text),
77
+ ...(onSubmit ? { onSubmit: () => { onSubmit(); return false } } : {}),
78
+ ...(className || editorAttributes
79
+ ? {
80
+ editorAttributes: {
81
+ ...(editorAttributes ?? {}),
82
+ ...(className ? { class: className } : {}),
83
+ },
84
+ }
85
+ : {}),
86
+ }),
87
+ // Re-mount when collab toggles. Other props (multiline, name, etc) are
88
+ // stable per mount under the upstream gate.
89
+ [collabActive],
90
+ )
91
+
92
+ // Mirror the editor's editable state with the prop. `useEditor` snapshots
93
+ // `editable` at first call, so we update it imperatively on changes.
94
+ useEffect(() => {
95
+ if (!editor) return
96
+ editor.setEditable(!disabled)
97
+ }, [editor, disabled])
98
+
99
+ // First-load seed when collab is active. Collaboration starts the editor
100
+ // empty regardless of `defaultValue`; once the provider syncs the room
101
+ // state from the server we check whether the field's `Y.XmlFragment`
102
+ // was ever written. Empty + we have an initial value = first session for
103
+ // this record — push the SSR-rendered default into the editor once.
104
+ //
105
+ // Race caveat: two peers simultaneously mounting against a brand-new
106
+ // record (both seeing `fragment.length === 0`) can both seed and produce
107
+ // duplicated text. Same window as `TiptapEditor`'s rich-text seed path.
108
+ // Acceptable for now; can be tightened later via a deterministic
109
+ // first-writer election or a server-side seed handoff.
110
+ const [hasSeeded, setHasSeeded] = useState(false)
111
+ useEffect(() => {
112
+ if (!editor || !collabActive || !room || hasSeeded) return
113
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
114
+ const ydoc = room.ydoc as any
115
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
116
+ const provider = room.provider as any
117
+ if (!ydoc || !provider) return
118
+
119
+ const trySeed = (): void => {
120
+ try {
121
+ const fragment = ydoc.getXmlFragment(name)
122
+ if (fragment && fragment.length === 0 && defaultValue) {
123
+ editor.commands.setContent(plainTextToDoc(defaultValue, multiline))
124
+ }
125
+ setHasSeeded(true)
126
+ } catch {
127
+ setHasSeeded(true)
128
+ }
129
+ }
130
+
131
+ if (provider.synced) {
132
+ trySeed()
133
+ return
134
+ }
135
+ provider.once('synced', trySeed)
136
+ return () => {
137
+ try { provider.off?.('synced', trySeed) } catch { /* ignore */ }
138
+ }
139
+ // Seed once per editor instance — keyed remount above resets `hasSeeded`.
140
+ // eslint-disable-next-line react-hooks/exhaustive-deps
141
+ }, [editor, collabActive, room])
142
+
143
+ // Bubble the editor's blur event up to the host. Tiptap exposes this via
144
+ // `editor.on('blur', ...)`. The simpler `onBlur` prop on `EditorContent`
145
+ // fires on the DOM node, but selection inside contenteditable can land on
146
+ // child nodes; the Tiptap event is the canonical "editor lost focus".
147
+ useEffect(() => {
148
+ if (!editor) return
149
+ const handler = (): void => onBlur()
150
+ editor.on('blur', handler)
151
+ return () => { editor.off('blur', handler) }
152
+ }, [editor, onBlur])
153
+
154
+ // Best-effort getText safety net — onUpdate should fire on every
155
+ // y-prosemirror sync, but if a remote update somehow doesn't trigger
156
+ // `onUpdate`, the wrapper's hidden input goes stale. Re-emit on every
157
+ // editor render tick. No-op when text matches the last emit.
158
+ useEffect(() => {
159
+ if (!editor) return
160
+ onChange(plainTextOf(editor))
161
+ // eslint-disable-next-line react-hooks/exhaustive-deps
162
+ }, [editor])
163
+
164
+ return <EditorContent editor={editor} />
165
+ }
@@ -13,7 +13,12 @@ import { Table, TableRow, TableCell, TableHeader } from '@tiptap/extension-table
13
13
  import { Details, DetailsSummary, DetailsContent } from '@tiptap/extension-details'
14
14
  import { Grid, GridColumn } from '../extensions/GridExtension.js'
15
15
  import { Popover } from '@base-ui/react/popover'
16
- import type { FieldRendererProps } from '@pilotiq/pilotiq/react'
16
+ import type {
17
+ FieldRendererProps,
18
+ CollabRoom,
19
+ CollabExtensionFactory,
20
+ } from '@pilotiq/pilotiq/react'
21
+ import { useCollabRoom, getCollabExtensions } from '@pilotiq/pilotiq/react'
17
22
  import { useAiSuggestionBridge } from './useAiSuggestionBridge.js'
18
23
  import type { BlockMeta } from '../Block.js'
19
24
  import type { ToolbarGroups, RichTextStorage, ColorSwatch } from '../RichTextField.js'
@@ -66,7 +71,7 @@ export function TiptapEditor(props: FieldRendererProps) {
66
71
  const storage = (props.el['storage'] as RichTextStorage | undefined) ?? 'json'
67
72
  const initialValue = serializeForHidden(props.defaultValue, storage)
68
73
  return (
69
- <div className="flex flex-col gap-1">
74
+ <div className="flex flex-col">
70
75
  <input type="hidden" name={props.name} value={initialValue} />
71
76
  <div className="prose prose-sm max-w-none min-h-[180px] rounded-md border border-input bg-transparent px-10 py-3 text-sm text-muted-foreground">
72
77
  {props.placeholder ?? 'Start writing…'}
@@ -75,11 +80,51 @@ export function TiptapEditor(props: FieldRendererProps) {
75
80
  )
76
81
  }
77
82
 
78
- return <ClientEditor {...props} />
83
+ return <CollabAwareTiptap {...props} />
79
84
  }
80
85
 
81
- function ClientEditor(props: FieldRendererProps) {
82
- const { el, name, defaultValue, placeholder, disabled } = props
86
+ /**
87
+ * Bridges pilotiq's open-core `CollabRoomContext` + `CollabExtensionFactory`
88
+ * registry into the Tiptap renderer. When `@pilotiq-pro/collab` is wired
89
+ * AND a `<RecordCollabRoom>` is mounted up-tree, the room flips non-null;
90
+ * keying `ClientEditor` on that toggle remounts the editor cleanly so the
91
+ * `Collaboration` extension can install (Tiptap can't swap it at runtime).
92
+ *
93
+ * No-op shell when collab isn't installed — `room` stays `null`,
94
+ * `getCollabExtensions()` returns `null`, and `ClientEditor` runs its
95
+ * plain Tiptap path with the same shape as before.
96
+ */
97
+ function CollabAwareTiptap(props: FieldRendererProps) {
98
+ const room = useCollabRoom()
99
+ const factory = getCollabExtensions()
100
+ // Per-field opt-out — `RichTextField.collab(false)` stamps `meta.collab`
101
+ // explicitly false, overriding the panel-wide auto-on default. Useful for
102
+ // fields that should stay device-local (private notes, draft scratch
103
+ // space, etc.) inside an otherwise collab-on form.
104
+ const fieldCollab = props.el['collab'] as boolean | undefined
105
+ const collabActive = !!(room && factory) && fieldCollab !== false
106
+ return (
107
+ <ClientEditor
108
+ key={collabActive ? 'collab' : 'local'}
109
+ {...props}
110
+ room={collabActive ? room : null}
111
+ factory={collabActive ? factory : null}
112
+ collabActive={collabActive}
113
+ />
114
+ )
115
+ }
116
+
117
+ interface ClientEditorProps extends FieldRendererProps {
118
+ /** Active record room, or `null` when no `<RecordCollabRoom>` is mounted. */
119
+ room: CollabRoom | null
120
+ /** Registered collab extension factory, or `null` when no plugin registered. */
121
+ factory: CollabExtensionFactory | null
122
+ /** Convenience flag — `true` iff both `room` AND `factory` are non-null. */
123
+ collabActive: boolean
124
+ }
125
+
126
+ function ClientEditor(props: ClientEditorProps) {
127
+ const { el, name, defaultValue, placeholder, disabled, room, factory, collabActive } = props
83
128
 
84
129
  const blocks = (el['blocks'] as BlockMeta[] | undefined) ?? []
85
130
  const slashEnabled = (el['slashCommand'] as boolean | undefined) ?? true
@@ -165,13 +210,35 @@ function ClientEditor(props: FieldRendererProps) {
165
210
  // the extension config to re-evaluate, triggering a full editor reset).
166
211
  const editorRef = useRef<Editor | null>(null)
167
212
 
213
+ // Resolve the collab-attached extensions once per editor build.
214
+ // `Collaboration` is constructed eagerly here (during `useEditor`'s
215
+ // first call); the keyed remount above guarantees we never swap it.
216
+ const collabExtensions = useMemo(() => {
217
+ if (!collabActive || !room || !factory) return [] as unknown[]
218
+ return factory({
219
+ ydoc: room.ydoc,
220
+ provider: room.provider,
221
+ fieldName: name,
222
+ ...(room.user ? { user: room.user } : {}),
223
+ })
224
+ // Intentionally deps-stable across renders within the same collab
225
+ // mount — the keyed wrapper above remounts us when collab toggles.
226
+ // eslint-disable-next-line react-hooks/exhaustive-deps
227
+ }, [collabActive])
228
+
168
229
  const editor = useEditor({
169
230
  editable: !disabled,
170
231
  extensions: [
171
232
  // StarterKit 3.22+ ships Link AND Underline; configure through the
172
233
  // kit rather than re-adding (else "Duplicate extension names" warns).
234
+ // `Collaboration` brings its own Yjs-backed history — disable
235
+ // StarterKit's local `undoRedo` extension when collab is active
236
+ // (renamed from `history` in Tiptap v3.x; passing `history: false`
237
+ // silently no-ops and produces a runtime "not compatible with
238
+ // @tiptap/extension-undo-redo" warning).
173
239
  StarterKit.configure({
174
240
  link: { openOnClick: false, autolink: true },
241
+ ...(collabActive ? { undoRedo: false } : {}),
175
242
  }),
176
243
  Subscript,
177
244
  Superscript,
@@ -252,8 +319,21 @@ function ClientEditor(props: FieldRendererProps) {
252
319
  // inline strikethrough + Approve/Reject chip widgets. Idle until the
253
320
  // host calls `editor.commands.addAiSuggestion(...)`.
254
321
  AiSuggestionExtension,
322
+ // Realtime-collab extensions (Yjs `Collaboration` + cursor) — empty
323
+ // when no `<RecordCollabRoom>` is mounted up-tree, or when no plugin
324
+ // registered a factory via `registerCollabExtensions`.
325
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
326
+ ...(collabExtensions as any[]),
255
327
  ],
256
- content: initialContent ?? '',
328
+ // Collaboration takes ownership of the document — `content` would race
329
+ // the Y.XmlFragment sync. Seed instead via the post-`synced` effect
330
+ // below so existing DB content lands once and only once. The non-collab
331
+ // branch also gates on `isTiptapShapedContent` so leftover content from
332
+ // a previous editor (e.g. Lexical's `{ root: {...} }`) doesn't crash
333
+ // the schema-strict node parser on first paint.
334
+ content: collabActive
335
+ ? ''
336
+ : (initialContent !== undefined && isTiptapShapedContent(initialContent) ? initialContent : ''),
257
337
  onUpdate: ({ editor: ed }) => {
258
338
  // Debounce serialization — every keystroke fires onUpdate.
259
339
  if (debounceRef.current) clearTimeout(debounceRef.current)
@@ -338,6 +418,55 @@ function ClientEditor(props: FieldRendererProps) {
338
418
  // scratch on every keystroke.
339
419
  useEffect(() => { editorRef.current = editor ?? null }, [editor])
340
420
 
421
+ // First-load seed when collab is active. Collaboration starts the
422
+ // editor empty regardless of `defaultValue`; once the WebsocketProvider
423
+ // syncs the room state from the server we check whether the field's
424
+ // Y.XmlFragment was ever written. Empty + we have an initial value =
425
+ // first session for this record — push the DB content into the ydoc
426
+ // exactly once. Non-empty = the room already has authoritative state;
427
+ // don't overwrite.
428
+ useEffect(() => {
429
+ if (!editor || !collabActive || !room) return
430
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
431
+ const provider = room.provider as any
432
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
433
+ const ydoc = room.ydoc as any
434
+ if (!provider || !ydoc) return
435
+
436
+ const trySeed = () => {
437
+ try {
438
+ const fragment = ydoc.getXmlFragment(name)
439
+ if (
440
+ fragment &&
441
+ fragment.length === 0 &&
442
+ initialContent !== undefined &&
443
+ initialContent !== null &&
444
+ initialContent !== '' &&
445
+ isTiptapShapedContent(initialContent)
446
+ ) {
447
+ // setContent dispatches a Tiptap transaction; the bound
448
+ // y-prosemirror binding (inside Collaboration) mirrors it
449
+ // into the fragment so every peer sees the seeded state.
450
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
451
+ editor.commands.setContent(initialContent as any)
452
+ }
453
+ } catch { /* ignore — seed is best-effort */ }
454
+ }
455
+
456
+ if (provider.synced) {
457
+ trySeed()
458
+ return
459
+ }
460
+ provider.once('synced', trySeed)
461
+ return () => {
462
+ try { provider.off?.('synced', trySeed) } catch { /* ignore */ }
463
+ }
464
+ // `initialContent` resolves once per mount (parsed from defaultValue
465
+ // at the top of this body). The keyed remount above guarantees we
466
+ // get a fresh closure per collab session.
467
+ // eslint-disable-next-line react-hooks/exhaustive-deps
468
+ }, [editor, collabActive, room, name])
469
+
341
470
  // Cross-package suggestion bridge — sync the host's
342
471
  // `<PendingSuggestionsContext>` queue with the editor's `AiSuggestion`
343
472
  // extension. No-op when no provider is mounted (default no-op context).
@@ -348,7 +477,7 @@ function ClientEditor(props: FieldRendererProps) {
348
477
  const tick = useEditorTick(editor)
349
478
 
350
479
  return (
351
- <div className="relative flex flex-col gap-1">
480
+ <div className="relative flex flex-col">
352
481
  <input type="hidden" name={name} value={serialized} />
353
482
  {editor && toolbarGroups && toolbarGroups.length > 0 && (
354
483
  <Toolbar
@@ -513,6 +642,25 @@ function SlashPopover({
513
642
  )
514
643
  }
515
644
 
645
+ /**
646
+ * Loose shape check — returns `true` only when the value looks like a Tiptap
647
+ * (ProseMirror JSON) document: either an HTML string or an object that opens
648
+ * with `{ type: 'doc' }` at the top level. Used by the collab seed effect to
649
+ * skip leftover content from previous editors (notably Lexical's
650
+ * `{ root: {...} }` envelope) without crashing Tiptap's strict node parser.
651
+ *
652
+ * The conservative posture: if we can't recognise the shape we don't seed.
653
+ * Worst case the user sees an empty editor on the first collab session and
654
+ * types fresh — better than the editor showing nothing because a parse threw.
655
+ */
656
+ function isTiptapShapedContent(raw: unknown): boolean {
657
+ if (typeof raw === 'string') return true // HTML or raw text — Tiptap parses both.
658
+ if (raw === null || typeof raw !== 'object') return false
659
+ const obj = raw as { type?: unknown; content?: unknown; root?: unknown }
660
+ if (obj.root !== undefined) return false // Lexical state envelope — never Tiptap.
661
+ return obj.type === 'doc' // ProseMirror JSON always opens with `type:'doc'`.
662
+ }
663
+
516
664
  function parseInitialContent(raw: unknown): object | string | undefined {
517
665
  if (raw === undefined || raw === null || raw === '') return undefined
518
666
  if (typeof raw === 'object') return raw as object
package/src/register.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { registerFieldRenderer } from '@pilotiq/pilotiq/react'
1
+ import { registerFieldRenderer, registerCollabTextRenderer } from '@pilotiq/pilotiq/react'
2
2
  import { registerRichTextRenderer } from '@pilotiq/pilotiq/richtext'
3
3
  import { TiptapEditor } from './react/TiptapEditor.js'
4
+ import { CollabTextRenderer } from './react/CollabTextRenderer.js'
4
5
  import { renderRichTextToHtml, isRichTextValue } from './render.js'
5
6
 
6
7
  /**
@@ -24,4 +25,10 @@ import { renderRichTextToHtml, isRichTextValue } from './render.js'
24
25
  export function registerTiptap(): void {
25
26
  registerFieldRenderer('richtext', TiptapEditor)
26
27
  registerRichTextRenderer(renderRichTextToHtml, isRichTextValue)
28
+ // Phase B — opt every plain-text field in the panel into y-prosemirror
29
+ // backing when collab is on. `TextLikeInput` checks this registry; if it's
30
+ // populated AND a `<RecordCollabRoom>` is up-tree AND the field hasn't opted
31
+ // out via `.collab(false)`, the renderer mounts `CollabTextRenderer`
32
+ // instead of the legacy `Y.Text` + `computeDelta` + `preserveCursor` path.
33
+ registerCollabTextRenderer(CollabTextRenderer)
27
34
  }