@pilotiq/pilotiq 0.12.0 → 0.13.0

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.
Files changed (50) hide show
  1. package/.turbo/turbo-build.log +2 -2
  2. package/CHANGELOG.md +13 -0
  3. package/dist/react/FormCollabBindingRegistry.d.ts +17 -98
  4. package/dist/react/FormCollabBindingRegistry.d.ts.map +1 -1
  5. package/dist/react/FormCollabBindingRegistry.js.map +1 -1
  6. package/dist/react/FormStateContext.d.ts +1 -35
  7. package/dist/react/FormStateContext.d.ts.map +1 -1
  8. package/dist/react/FormStateContext.js +7 -91
  9. package/dist/react/FormStateContext.js.map +1 -1
  10. package/dist/react/RowCoordsContext.d.ts +19 -0
  11. package/dist/react/RowCoordsContext.d.ts.map +1 -0
  12. package/dist/react/RowCoordsContext.js +6 -0
  13. package/dist/react/RowCoordsContext.js.map +1 -0
  14. package/dist/react/fields/BuilderInput.d.ts.map +1 -1
  15. package/dist/react/fields/BuilderInput.js +14 -9
  16. package/dist/react/fields/BuilderInput.js.map +1 -1
  17. package/dist/react/fields/MarkdownInput.d.ts.map +1 -1
  18. package/dist/react/fields/MarkdownInput.js +35 -125
  19. package/dist/react/fields/MarkdownInput.js.map +1 -1
  20. package/dist/react/fields/RepeaterInput.d.ts.map +1 -1
  21. package/dist/react/fields/RepeaterInput.js +26 -17
  22. package/dist/react/fields/RepeaterInput.js.map +1 -1
  23. package/dist/react/fields/TextLikeInput.d.ts +11 -9
  24. package/dist/react/fields/TextLikeInput.d.ts.map +1 -1
  25. package/dist/react/fields/TextLikeInput.js +59 -189
  26. package/dist/react/fields/TextLikeInput.js.map +1 -1
  27. package/dist/react/formStateHelpers.d.ts +0 -15
  28. package/dist/react/formStateHelpers.d.ts.map +1 -1
  29. package/dist/react/formStateHelpers.js +0 -91
  30. package/dist/react/formStateHelpers.js.map +1 -1
  31. package/dist/react/index.d.ts +1 -1
  32. package/dist/react/index.d.ts.map +1 -1
  33. package/dist/react/index.js.map +1 -1
  34. package/package.json +1 -1
  35. package/src/react/FormCollabBindingRegistry.ts +17 -91
  36. package/src/react/FormStateContext.tsx +6 -125
  37. package/src/react/RowCoordsContext.tsx +23 -0
  38. package/src/react/fields/BuilderInput.tsx +22 -10
  39. package/src/react/fields/MarkdownInput.tsx +42 -129
  40. package/src/react/fields/RepeaterInput.tsx +41 -16
  41. package/src/react/fields/TextLikeInput.tsx +67 -225
  42. package/src/react/formStateHelpers.test.ts +0 -99
  43. package/src/react/formStateHelpers.ts +0 -83
  44. package/src/react/index.ts +0 -2
  45. package/dist/react/fields/textDelta.d.ts +0 -44
  46. package/dist/react/fields/textDelta.d.ts.map +0 -1
  47. package/dist/react/fields/textDelta.js +0 -80
  48. package/dist/react/fields/textDelta.js.map +0 -1
  49. package/src/react/fields/textDelta.test.ts +0 -141
  50. package/src/react/fields/textDelta.ts +0 -86
@@ -1,12 +1,12 @@
1
- import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
1
+ import React, { useCallback, useEffect, useRef, useState } from 'react'
2
2
  import type { ElementMeta } from '../../schema/Element.js'
3
- import type { TextBinding } from '../FormCollabBindingRegistry.js'
4
3
  import { useFieldState } from '../FormStateContext.js'
5
4
  import { useCollabRoom } from '../CollabRoomContext.js'
6
5
  import { getCollabTextRenderer, type CollabTextRenderer } from '../CollabTextRendererRegistry.js'
6
+ import { useRowCoords } from '../RowCoordsContext.js'
7
+ import { parseRowFieldPath } from '../formStateHelpers.js'
7
8
  import { Input } from '../ui/input.js'
8
9
  import { Textarea } from '../ui/textarea.js'
9
- import { computeDelta, preserveCursor } from './textDelta.js'
10
10
 
11
11
  /**
12
12
  * Bridge between controlled (FormStateProvider) and uncontrolled
@@ -15,15 +15,17 @@ import { computeDelta, preserveCursor } from './textDelta.js'
15
15
  * fires the live trigger on change/blur according to the field's `live`
16
16
  * config. Outside a controlled form, falls back to plain `defaultValue`.
17
17
  *
18
- * **Phase F.6character-level CRDT branch.** When a `<RecordCollabRoom>`
19
- * is mounted up-tree AND `@pilotiq-pro/collab`'s binding registered a
20
- * `TextBinding` for this field (text-shaped fieldType + `.collab() !== false`),
21
- * the input takes the `BoundTextInput` path: edits emit `TextDelta`s to
22
- * the binding's `Y.Text`, remote changes flow back via `observe`, and
23
- * cursor position survives both. The legacy whole-string LWW path
24
- * still runs for non-text fields, non-collab forms, and masked inputs
25
- * (mask + character-level CRDT is incompatible peers would see raw
26
- * keystrokes desynced from the rendered mask).
18
+ * **Collab branchTiptap-backed `Y.XmlFragment`.** When a
19
+ * `<RecordCollabRoom>` is mounted up-tree AND `@pilotiq/tiptap`'s
20
+ * `registerTiptap()` registered a collab text renderer, the input
21
+ * mounts the Tiptap-backed editor against a `Y.XmlFragment` keyed by
22
+ * either the bare field name (top-level) or
23
+ * `${arrayName}.${rowId}.${fieldName}` (Repeater / Builder row leaves
24
+ * via `useRowCoords()`). Selections anchor to `Y.RelativePosition` via
25
+ * y-prosemirror, so cursors survive both mid-word remote edits and
26
+ * concurrent inserts. Masked fields fall through to the legacy
27
+ * whole-string LWW path (mask + character-level CRDT is incompatible
28
+ * — peers would see raw keystrokes desynced from the rendered mask).
27
29
  */
28
30
  export function TextLikeInput({
29
31
  el, name, common, type, extraProps, multiline, applyMask,
@@ -42,6 +44,7 @@ export function TextLikeInput({
42
44
  const fs = useFieldState(name)
43
45
  const room = useCollabRoom()
44
46
  const collabRenderer = getCollabTextRenderer()
47
+ const rowCoords = useRowCoords()
45
48
  const liveCfg = el['live']
46
49
  const liveOpts = (typeof liveCfg === 'object' && liveCfg !== null
47
50
  ? liveCfg as { onBlur?: boolean; debounce?: number }
@@ -49,35 +52,48 @@ export function TextLikeInput({
49
52
  const onBlurMode = liveOpts.onBlur === true
50
53
  const mask = applyMask ?? identity
51
54
 
52
- // Phase F.6 character-level CRDT path. Masking is mutually exclusive
53
- // with character-level CRDT (peers would see raw keystrokes diverged
54
- // from the local mask render); masked fields fall through to LWW.
55
- // We read the mask from the field meta directly — `applyMask` is a
56
- // `useCallback`-wrapped fn that's *always* defined (identity when no
57
- // mask), so its truthiness can't gate the branch.
55
+ // Masking is mutually exclusive with character-level CRDT (peers would
56
+ // see raw keystrokes diverged from the local mask render); masked
57
+ // fields fall through to LWW. We read the mask from the field meta
58
+ // directly — `applyMask` is a `useCallback`-wrapped fn that's *always*
59
+ // defined (identity when no mask), so its truthiness can't gate the
60
+ // branch.
58
61
  const hasMask = typeof el['mask'] === 'string'
59
62
 
60
- // Phase B — Tiptap-backed plain-text editor for collab text fields.
61
- // When a `<RecordCollabRoom>` is mounted up-tree AND `@pilotiq/tiptap`'s
62
- // `registerTiptap()` registered a collab text renderer, take the new path:
63
- // the editor anchors selections to Yjs `RelativePosition` (via y-prosemirror)
64
- // instead of integer string offsets, fixing the cursor-jump + two-peer
65
- // concurrent-insert races that the legacy `Y.Text` + `computeDelta` path
66
- // can't resolve. Dotted-path row leaves (Repeater / Builder) stay on the
67
- // legacy `fs.textBinding` path — per-row collab editor support is a
68
- // separate follow-up.
63
+ // Collab branch — Tiptap-backed plain-text editor. Top-level fields
64
+ // use the bare `name` as the fragment-key; Repeater / Builder row
65
+ // leaves compose `${arrayName}.${rowId}.${fieldName}` from
66
+ // `useRowCoords()` so the Y.XmlFragment survives row reorders (keyed
67
+ // by the stable rowId, not the array index). The hidden FormData
68
+ // input keeps the original dotted path so submission lands on the
69
+ // server at the right slot.
70
+ //
71
+ // Dotted paths that don't match a row shape (no rowCoords OR
72
+ // `parseRowFieldPath` returns null — nested row arrays, malformed
73
+ // names) skip the collab path and fall through to the controlled /
74
+ // uncontrolled branches below.
69
75
  const fieldCollab = el['collab'] as boolean | undefined
76
+ const fragmentKey: string | null = (() => {
77
+ if (!name.includes('.')) return name
78
+ if (!rowCoords) return null
79
+ const parsed = parseRowFieldPath(name)
80
+ if (!parsed) return null
81
+ if (parsed.arrayName !== rowCoords.arrayName) return null
82
+ if (parsed.index !== rowCoords.rowIndex) return null
83
+ return `${rowCoords.arrayName}.${rowCoords.rowId}.${parsed.fieldName}`
84
+ })()
70
85
  if (
71
86
  room &&
72
87
  collabRenderer &&
73
88
  fieldCollab !== false &&
74
89
  !hasMask &&
75
- !name.includes('.')
90
+ fragmentKey !== null
76
91
  ) {
77
92
  return (
78
93
  <CollabTextField
79
94
  Renderer={collabRenderer}
80
- name={name}
95
+ fragmentKey={fragmentKey}
96
+ hiddenInputName={name}
81
97
  multiline={multiline}
82
98
  defaultValue={stringValue(common['defaultValue'])}
83
99
  {...(common['placeholder'] !== undefined ? { placeholder: String(common['placeholder']) } : {})}
@@ -90,21 +106,6 @@ export function TextLikeInput({
90
106
  )
91
107
  }
92
108
 
93
- if (fs.textBinding && !hasMask) {
94
- return (
95
- <BoundTextInput
96
- binding={fs.textBinding}
97
- name={name}
98
- triggerLive={fs.triggerLive}
99
- onBlurMode={onBlurMode}
100
- common={common}
101
- extraProps={extraProps}
102
- type={type}
103
- multiline={multiline}
104
- />
105
- )
106
- }
107
-
108
109
  if (fs.controlled) {
109
110
  const ctxValue = fs.value !== undefined && fs.value !== null ? String(fs.value) : ''
110
111
  const onChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>): void => {
@@ -144,174 +145,7 @@ export function TextLikeInput({
144
145
  }
145
146
 
146
147
  /**
147
- * Phase F.6 CRDT-bound text input. Owns its own controlled state
148
- * because the binding's `Y.Text` is the source of truth (not the
149
- * form's `values` map). Mirrors every committed value back into the
150
- * form context via `fs.setValue` so submission / live re-resolve see
151
- * the latest string.
152
- *
153
- * Lifecycle:
154
- * - Mount: seed local state from `binding.read()`; mirror it into
155
- * the form's `values` map.
156
- * - Local edit: compute a `TextDelta` (insert / delete / replace)
157
- * from the before/after strings and `applyDelta` to the binding.
158
- * Eagerly update local state in the same React render so the
159
- * controlled input doesn't lag the keystroke.
160
- * - Remote edit: `binding.observe` fires with the post-change
161
- * string; we replace local state and best-effort preserve the
162
- * local cursor via `preserveCursor`. The local-echo of our own
163
- * `applyDelta` is collapsed by the value-equality check.
164
- * - IME composition: `applyDelta` is deferred to `compositionend`
165
- * so the binding never sees intermediate composing chars (which
166
- * would emit one delta per keystroke and confuse downstream
167
- * observers).
168
- */
169
- function BoundTextInput({
170
- binding, name, triggerLive, onBlurMode, common, extraProps, type, multiline,
171
- }: {
172
- binding: TextBinding
173
- name: string
174
- triggerLive: (valueOverride?: unknown) => void
175
- onBlurMode: boolean
176
- common: Record<string, unknown>
177
- extraProps: Record<string, unknown>
178
- type: string
179
- multiline: boolean
180
- }): React.ReactElement {
181
- const fs = useFieldState(name)
182
- // SSR-rendered default. Captured once at mount; used as display
183
- // fallback while the room's `Y.Text` is still empty (the seed race
184
- // for Y.Text isn't safe across concurrent first-mounters, so no peer
185
- // populates it client-side — see `@pilotiq-pro/collab` for the
186
- // rationale). First user edit emits a replace-from-empty delta that
187
- // atomically lifts the displayed value into the CRDT.
188
- // eslint-disable-next-line react-hooks/exhaustive-deps
189
- const fallback = useMemo(() => stringValue(fs.value), [])
190
- const [value, setValueLocal] = useState<string>(() => binding.read() || fallback)
191
- const valueRef = useRef<string>(value)
192
- const isComposing = useRef<boolean>(false)
193
- const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement | null>(null)
194
-
195
- useEffect(() => { valueRef.current = value }, [value])
196
-
197
- // Stable ref to the form-mirror writer so the observer effect below
198
- // doesn't tear down on every render (fs.setValue is a fresh arrow on
199
- // every useFieldState call).
200
- const mirrorRef = useRef<(v: string) => void>(() => {})
201
- useEffect(() => {
202
- mirrorRef.current = (v: string): void => { fs.setValue(v) }
203
- })
204
-
205
- // On mount / binding swap: read the binding's current state. If
206
- // non-empty (i.e. someone else has already typed), display it and
207
- // mirror into the form values map. If empty, leave the fallback
208
- // showing — no client-side seed (see file-header comment).
209
- useEffect(() => {
210
- const initial = binding.read()
211
- if (initial.length > 0) {
212
- setValueLocal(initial)
213
- valueRef.current = initial
214
- mirrorRef.current(initial)
215
- }
216
- }, [binding])
217
-
218
- // Subscribe to text-CRDT changes. Yjs fires this for BOTH local and
219
- // remote transactions — local echoes are collapsed by the
220
- // `next === prev` guard.
221
- useEffect(() => {
222
- const unsubscribe = binding.observe((next) => {
223
- const prev = valueRef.current
224
- if (next === prev) return
225
- const el = inputRef.current
226
- const cursor = el?.selectionStart ?? next.length
227
- const restored = preserveCursor(prev, next, cursor)
228
- setValueLocal(next)
229
- valueRef.current = next
230
- mirrorRef.current(next)
231
- // Defer cursor restore until after React commits. Only reapply
232
- // when the input is still focused — yanking the selection on a
233
- // blurred field would steal focus across the page.
234
- requestAnimationFrame(() => {
235
- if (!el) return
236
- if (document.activeElement !== el) return
237
- try { el.setSelectionRange(restored, restored) } catch { /* setSelectionRange unsupported on some input types — defensive */ }
238
- })
239
- })
240
- return unsubscribe
241
- }, [binding])
242
-
243
- const commitDelta = useCallback((after: string): void => {
244
- // Compute the delta against the binding's *current* Y.Text contents
245
- // — not the renderer's `before` ref. The two can diverge in three
246
- // cases that all converge correctly under this approach:
247
- // 1. First edit when Y.Text is empty: delta = `insert@0 <whole>`,
248
- // which atomically lifts the displayed fallback into the CRDT
249
- // without a separate seed op.
250
- // 2. After a remote-applied update: Y.Text holds the peer's value;
251
- // computing against it avoids "ghost" deltas that re-emit ops
252
- // against a stale local ref.
253
- // 3. After a server-resolve `triggerLive` replace: same as (2).
254
- const before = binding.read()
255
- if (after === before) return
256
- const delta = computeDelta(before, after)
257
- if (!delta) return
258
- // Pre-stamp `valueRef.current = after` BEFORE `applyDelta`. Y.Text's
259
- // observe fires synchronously inside `applyDelta` for our own write,
260
- // so without this the observer would see `prev=before, next=after`
261
- // and run `preserveCursor` — which is designed for *remote* edits
262
- // and clobbers the user's caret on local typing (typed '1' at pos 0
263
- // would jump cursor forward by delta-length and the next keystroke
264
- // would insert at the wrong index, producing scrambled output).
265
- // With `valueRef` already at `after`, the observer's `next === prev`
266
- // short-circuit fires and the cursor is left alone for local echoes.
267
- valueRef.current = after
268
- binding.applyDelta(delta)
269
- setValueLocal(after)
270
- mirrorRef.current(after)
271
- if (!onBlurMode) triggerLive(after)
272
- }, [binding, onBlurMode, triggerLive])
273
-
274
- const onChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>): void => {
275
- if (isComposing.current) {
276
- // IME mid-composition — paint locally, hold the delta until commit.
277
- setValueLocal(e.target.value)
278
- return
279
- }
280
- commitDelta(e.target.value)
281
- }
282
-
283
- const onCompositionStart = (): void => { isComposing.current = true }
284
- const onCompositionEnd = (e: React.CompositionEvent<HTMLInputElement | HTMLTextAreaElement>): void => {
285
- isComposing.current = false
286
- commitDelta(e.currentTarget.value)
287
- }
288
-
289
- const onBlur = (): void => {
290
- if (onBlurMode) triggerLive(valueRef.current)
291
- }
292
-
293
- const setRef = (el: HTMLInputElement | HTMLTextAreaElement | null): void => {
294
- inputRef.current = el
295
- }
296
-
297
- const props = {
298
- ...common,
299
- ...extraProps,
300
- defaultValue: undefined,
301
- value,
302
- onChange,
303
- onBlur,
304
- onCompositionStart,
305
- onCompositionEnd,
306
- ref: setRef,
307
- }
308
-
309
- if (multiline) return <Textarea {...(props as React.ComponentProps<typeof Textarea>)} />
310
- return <Input {...(props as React.ComponentProps<typeof Input>)} type={type} />
311
- }
312
-
313
- /**
314
- * Phase B — wrapper around the registered Tiptap-backed collab editor.
148
+ * Wrapper around the registered Tiptap-backed collab editor.
315
149
  * Owns the local text mirror so the hidden `<input>` always carries the
316
150
  * editor's current value for FormData submission. When `FormStateProvider`
317
151
  * is mounted up-tree, also mirrors every update into the values map via
@@ -322,21 +156,29 @@ function BoundTextInput({
322
156
  * editor handles composition natively and y-prosemirror anchors selections
323
157
  * to `Yjs.RelativePosition`, so the cursor survives concurrent + mid-word
324
158
  * remote edits without any client-side bookkeeping.
159
+ *
160
+ * `fragmentKey` and `hiddenInputName` diverge for row-text leaves (Phase
161
+ * 1 of collab-row-text-tiptap-backed.md): the renderer's Y.XmlFragment is
162
+ * keyed by `${arrayName}.${rowId}.${fieldName}` so it survives row
163
+ * reorders, while the hidden FormData input keeps the dotted path
164
+ * (`items.0.title`) so submission lands at the right server-side slot.
165
+ * For top-level fields the two are identical.
325
166
  */
326
167
  function CollabTextField({
327
- Renderer, name, multiline, defaultValue, placeholder, disabled,
168
+ Renderer, fragmentKey, hiddenInputName, multiline, defaultValue, placeholder, disabled,
328
169
  triggerLive, setValue, controlled, onBlurMode,
329
170
  }: {
330
- Renderer: CollabTextRenderer
331
- name: string
332
- multiline: boolean
333
- defaultValue: string
334
- placeholder?: string
335
- disabled: boolean
336
- triggerLive: (valueOverride?: unknown) => void
337
- setValue: (v: unknown) => void
338
- controlled: boolean
339
- onBlurMode: boolean
171
+ Renderer: CollabTextRenderer
172
+ fragmentKey: string
173
+ hiddenInputName: string
174
+ multiline: boolean
175
+ defaultValue: string
176
+ placeholder?: string
177
+ disabled: boolean
178
+ triggerLive: (valueOverride?: unknown) => void
179
+ setValue: (v: unknown) => void
180
+ controlled: boolean
181
+ onBlurMode: boolean
340
182
  }): React.ReactElement {
341
183
  const [text, setText] = useState<string>(defaultValue)
342
184
  const textRef = useRef(text)
@@ -376,9 +218,9 @@ function CollabTextField({
376
218
 
377
219
  return (
378
220
  <>
379
- <input type="hidden" name={name} value={text} />
221
+ <input type="hidden" name={hiddenInputName} value={text} />
380
222
  <Renderer
381
- name={name}
223
+ name={fragmentKey}
382
224
  multiline={multiline}
383
225
  defaultValue={defaultValue}
384
226
  {...(placeholder !== undefined ? { placeholder } : {})}
@@ -4,7 +4,6 @@ import assert from 'node:assert/strict'
4
4
  import {
5
5
  collectFieldDefaults,
6
6
  collectRowArrayFieldNames,
7
- collectRowTextLeavesByArray,
8
7
  fieldOptsOutOfCollab,
9
8
  findFieldMeta,
10
9
  parseFormDataToNested,
@@ -492,104 +491,6 @@ describe('routeBindingWrite', () => {
492
491
  })
493
492
  })
494
493
 
495
- describe('collectRowTextLeavesByArray', () => {
496
- const textField = (name: string, fieldType: string = 'text', collab?: boolean): ElementMeta => ({
497
- type: 'field',
498
- fieldType,
499
- name,
500
- label: name,
501
- required: false,
502
- disabled: false,
503
- ...(collab === false ? { collab: false } : {}),
504
- } as ElementMeta)
505
-
506
- // Repeater meta carries the row schema under `template` (`children` is
507
- // the per-resolved-row child list, not the field-level template). Tests
508
- // must mirror what `RepeaterField.toMeta()` actually emits.
509
- const repeater = (name: string, template: ElementMeta[], collab?: boolean): ElementMeta => ({
510
- type: 'field',
511
- fieldType: 'repeater',
512
- name,
513
- label: name,
514
- required: false,
515
- disabled: false,
516
- template,
517
- ...(collab === false ? { collab: false } : {}),
518
- } as ElementMeta)
519
-
520
- it('collects text-shaped inner-field names per Repeater', () => {
521
- const meta = formMeta([
522
- repeater('tags', [
523
- textField('label', 'text'),
524
- textField('summary', 'textarea'),
525
- textField('count', 'number'),
526
- ]),
527
- ])
528
- const out = collectRowTextLeavesByArray(meta)
529
- assert.equal(out.size, 1)
530
- assert.deepEqual([...out.get('tags')!].sort(), ['label', 'summary'])
531
- })
532
-
533
- it('walks Builder block templates', () => {
534
- const meta = formMeta([
535
- {
536
- type: 'field',
537
- fieldType: 'builder',
538
- name: 'blocks',
539
- children: [],
540
- blocks: [
541
- { name: 'heading', template: [textField('text', 'text')] },
542
- { name: 'paragraph', template: [textField('body', 'markdown')] },
543
- ],
544
- } as unknown as ElementMeta,
545
- ])
546
- const out = collectRowTextLeavesByArray(meta)
547
- assert.deepEqual([...out.get('blocks')!].sort(), ['body', 'text'])
548
- })
549
-
550
- it('skips opted-out inner fields', () => {
551
- const meta = formMeta([
552
- repeater('tags', [
553
- textField('label', 'text'),
554
- textField('private', 'text', false), // .collab(false)
555
- ]),
556
- ])
557
- const out = collectRowTextLeavesByArray(meta)
558
- assert.deepEqual([...out.get('tags')!], ['label'])
559
- })
560
-
561
- it('omits opted-out top-level arrays', () => {
562
- const meta = formMeta([
563
- repeater('public', [textField('a', 'text')]),
564
- repeater('private', [textField('b', 'text')], false),
565
- ])
566
- const out = collectRowTextLeavesByArray(meta)
567
- assert.equal(out.has('public'), true)
568
- assert.equal(out.has('private'), false)
569
- })
570
-
571
- it('stops at nested array boundaries (no 5+ segment dotted paths)', () => {
572
- const meta = formMeta([
573
- repeater('outer', [
574
- textField('outerLabel', 'text'),
575
- repeater('inner', [textField('innerLabel', 'text')]),
576
- ]),
577
- ])
578
- const out = collectRowTextLeavesByArray(meta)
579
- assert.deepEqual([...out.get('outer')!], ['outerLabel'])
580
- assert.equal(out.has('inner'), false, 'nested Repeater not surfaced as a top-level array')
581
- })
582
-
583
- it('returns empty map when no Repeater/Builder has text leaves', () => {
584
- const meta = formMeta([
585
- textField('top', 'text'),
586
- repeater('numbers', [textField('count', 'number')]),
587
- ])
588
- const out = collectRowTextLeavesByArray(meta)
589
- assert.equal(out.size, 0)
590
- })
591
- })
592
-
593
494
  describe('fieldOptsOutOfCollab', () => {
594
495
  it('returns true only when the field carries an explicit collab=false', () => {
595
496
  const meta = formMeta([
@@ -379,86 +379,3 @@ export function collectRowArrayFieldNames(formMeta: ElementMeta): string[] {
379
379
  }
380
380
  }
381
381
 
382
- /**
383
- * Phase F.5c — text-shaped fieldTypes whose row-leaf values should be
384
- * routed through `Y.Text` instead of `Y.Map` LWW. Mirrors the same
385
- * allowlist `@pilotiq-pro/collab`'s top-level binding uses; consumers
386
- * registering character-level CRDT for additional plain-text-shaped
387
- * fields update both copies in lockstep until a cross-repo shared
388
- * constants module exists.
389
- */
390
- const ROW_TEXT_FIELD_TYPES: ReadonlySet<string> = new Set([
391
- 'text', 'textarea', 'email', 'slug', 'markdown',
392
- ])
393
-
394
- /**
395
- * Phase F.5c — per-Repeater/Builder set of inner-field names that
396
- * carry text-shaped leaves eligible for character-level CRDT. Drives
397
- * `useFieldState(dottedName).textBinding` resolution: only fields in
398
- * the per-array set go through `binding.getRowTextBinding`; everything
399
- * else stays on row-level Y.Map LWW.
400
- *
401
- * Repeater rows expose their schema directly under `meta.children`;
402
- * Builder rows nest schemas under `meta.blocks[i].template`. The
403
- * walker descends through every block's template so a `markdown` leaf
404
- * inside any block-type lands in the array's allowlist. Nested
405
- * Repeaters / Builders inside row schemas are out of scope v1 (their
406
- * dotted paths are 5+ segments and `parseRowFieldPath` rejects them).
407
- */
408
- export function collectRowTextLeavesByArray(formMeta: ElementMeta): Map<string, Set<string>> {
409
- const out = new Map<string, Set<string>>()
410
- walkTop(formMeta)
411
- return out
412
-
413
- function walkTop(node: ElementMeta): void {
414
- if (node.type === 'field') {
415
- const fieldType = String(node['fieldType'] ?? '')
416
- if (fieldType === 'repeater' || fieldType === 'builder') {
417
- if ((node as { collab?: boolean }).collab === false) return
418
- const name = String(node['name'] ?? '')
419
- if (!name) return
420
- const set = new Set<string>()
421
- // Repeater's `toMeta()` emits the row schema under `template` (not
422
- // `children` — that's per-resolved-row). Builder nests row schemas
423
- // under `blocks[i].template`. Reading `children` here pre-fix gave
424
- // every Repeater an empty text-leaf set → row text never CRDT'd.
425
- if (fieldType === 'repeater') walkRow((node as { template?: unknown }).template, set)
426
- else walkBlocks((node as { blocks?: unknown }).blocks, set)
427
- if (set.size > 0) out.set(name, set)
428
- return
429
- }
430
- }
431
- const children = node.children
432
- if (Array.isArray(children)) {
433
- for (const child of children) walkTop(child as ElementMeta)
434
- }
435
- }
436
-
437
- function walkRow(children: unknown, set: Set<string>): void {
438
- if (!Array.isArray(children)) return
439
- for (const child of children) walkRowEl(child as ElementMeta, set)
440
- }
441
-
442
- function walkRowEl(node: ElementMeta, set: Set<string>): void {
443
- if (node.type === 'field') {
444
- const fieldType = String(node['fieldType'] ?? '')
445
- if (fieldType === 'repeater' || fieldType === 'builder') return // nested array
446
- if ((node as { collab?: boolean }).collab === false) return
447
- const name = String(node['name'] ?? '')
448
- if (name && ROW_TEXT_FIELD_TYPES.has(fieldType)) set.add(name)
449
- return
450
- }
451
- const children = node.children
452
- if (Array.isArray(children)) {
453
- for (const child of children) walkRowEl(child as ElementMeta, set)
454
- }
455
- }
456
-
457
- function walkBlocks(blocks: unknown, set: Set<string>): void {
458
- if (!Array.isArray(blocks)) return
459
- for (const block of blocks) {
460
- const tpl = (block as { template?: unknown }).template
461
- walkRow(tpl, set)
462
- }
463
- }
464
- }
@@ -55,8 +55,6 @@ export {
55
55
  type FormCollabBinding,
56
56
  type FormCollabBindingFactory,
57
57
  type FormCollabBindingFactoryArgs,
58
- type TextBinding,
59
- type TextDelta,
60
58
  type RowsEvent,
61
59
  type RowBindingApi,
62
60
  } from './FormCollabBindingRegistry.js'
@@ -1,44 +0,0 @@
1
- import type { TextDelta } from '../FormCollabBindingRegistry.js';
2
- /**
3
- * Phase F.6 — derive a single character-level edit op from two strings.
4
- *
5
- * Strategy: find the longest common prefix and suffix between `before`
6
- * and `after`; whatever's left in the middle is the changed region.
7
- *
8
- * - middle-after empty + middle-before non-empty → `delete`
9
- * - middle-before empty + middle-after non-empty → `insert`
10
- * - both non-empty → `replace`
11
- * - both empty (identical strings) → `null`
12
- *
13
- * This correctly handles the common edit shapes: single-key insert,
14
- * single-key backspace, multi-char paste replacing a selection, IME
15
- * commits, accent-key composition. It does NOT preserve user intent
16
- * when the same character appears at multiple positions and the edit
17
- * could be attributed to either occurrence — Yjs's per-character
18
- * identity makes that distinction lossy at the string-diff layer
19
- * (the `Y.Text` itself maintains item identity internally). For v1
20
- * we accept the ambiguity; the CRDT semantics still converge.
21
- */
22
- export declare function computeDelta(before: string, after: string): TextDelta | null;
23
- /**
24
- * Phase F.6 — best-effort cursor anchor across a remote-applied edit.
25
- *
26
- * - Edit landed AFTER cursor (cursor inside the common prefix) → keep
27
- * cursor where it is.
28
- * - Edit landed BEFORE cursor → shift
29
- * cursor by `after.length − before.length` so its character-offset
30
- * into the post-edit string matches its pre-edit anchor.
31
- * - Edit landed OVERLAPPING the cursor → cursor
32
- * ends up at the boundary between the changed region and the
33
- * unchanged suffix (which `Math.max(0, cursor + delta)` produces
34
- * naturally and clamps to the new bounds).
35
- *
36
- * This is a heuristic, not a Yjs `RelativePosition`. Two peers typing
37
- * at the exact same insertion point can still see a one-character cursor
38
- * twitch on the remote-mirror side; v2 (in-input remote carets) would
39
- * upgrade to relative positions if/when a consumer asks. Native input
40
- * cursors are clamped to `[0, after.length]` by every browser, so this
41
- * function does the same to avoid `setSelectionRange` throwing.
42
- */
43
- export declare function preserveCursor(before: string, after: string, cursor: number): number;
44
- //# sourceMappingURL=textDelta.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"textDelta.d.ts","sourceRoot":"","sources":["../../../src/react/fields/textDelta.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAA;AAEhE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CA8B5E;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAWpF"}