@platejs/ai 49.2.15 → 50.1.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.
@@ -82,11 +82,2840 @@ var BaseAIPlugin = createTSlatePlugin({
82
82
  undo: bindFirst(undoAI, editor)
83
83
  }));
84
84
 
85
+ // src/lib/utils/getEditorPrompt.ts
86
+ import { isSelecting } from "@platejs/selection";
87
+ import { KEYS as KEYS3 } from "platejs";
88
+ var createPromptFromConfig = (config, params) => {
89
+ const { isBlockSelecting, isSelecting: isSelecting3 } = params;
90
+ if (isBlockSelecting && config.blockSelecting) {
91
+ return config.blockSelecting ?? config.default;
92
+ } else if (isSelecting3 && config.selecting) {
93
+ return config.selecting ?? config.default;
94
+ } else {
95
+ return config.default;
96
+ }
97
+ };
98
+ var getEditorPrompt = (editor, {
99
+ prompt = ""
100
+ }) => {
101
+ const params = {
102
+ editor,
103
+ isBlockSelecting: editor.getOption(
104
+ { key: KEYS3.blockSelection },
105
+ "isSelectingSome"
106
+ ),
107
+ isSelecting: isSelecting(editor)
108
+ };
109
+ let promptText = "";
110
+ if (typeof prompt === "function") {
111
+ promptText = prompt(params);
112
+ } else if (typeof prompt === "object") {
113
+ promptText = createPromptFromConfig(prompt, params);
114
+ } else {
115
+ promptText = prompt;
116
+ }
117
+ return promptText;
118
+ };
119
+
85
120
  // src/react/ai/AIPlugin.ts
86
121
  var AIPlugin = toPlatePlugin(BaseAIPlugin);
87
122
 
123
+ // src/react/ai/utils/aiCommentToRange.ts
124
+ import { deserializeMd } from "@platejs/markdown";
125
+ import {
126
+ NodeApi
127
+ } from "platejs";
128
+
129
+ // src/react/ai/utils/findTextRangeInBlock.tsx
130
+ import { distance } from "fastest-levenshtein";
131
+
132
+ // ../../node_modules/immer/dist/immer.mjs
133
+ var NOTHING = Symbol.for("immer-nothing");
134
+ var DRAFTABLE = Symbol.for("immer-draftable");
135
+ var DRAFT_STATE = Symbol.for("immer-state");
136
+ var errors = process.env.NODE_ENV !== "production" ? [
137
+ // All error codes, starting by 0:
138
+ function(plugin) {
139
+ return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
140
+ },
141
+ function(thing) {
142
+ return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;
143
+ },
144
+ "This object has been frozen and should not be mutated",
145
+ function(data) {
146
+ return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
147
+ },
148
+ "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
149
+ "Immer forbids circular references",
150
+ "The first or second argument to `produce` must be a function",
151
+ "The third argument to `produce` must be a function or undefined",
152
+ "First argument to `createDraft` must be a plain object, an array, or an immerable object",
153
+ "First argument to `finishDraft` must be a draft returned by `createDraft`",
154
+ function(thing) {
155
+ return `'current' expects a draft, got: ${thing}`;
156
+ },
157
+ "Object.defineProperty() cannot be used on an Immer draft",
158
+ "Object.setPrototypeOf() cannot be used on an Immer draft",
159
+ "Immer only supports deleting array indices",
160
+ "Immer only supports setting array indices and the 'length' property",
161
+ function(thing) {
162
+ return `'original' expects a draft, got: ${thing}`;
163
+ }
164
+ // Note: if more errors are added, the errorOffset in Patches.ts should be increased
165
+ // See Patches.ts for additional errors
166
+ ] : [];
167
+ function die(error, ...args) {
168
+ if (process.env.NODE_ENV !== "production") {
169
+ const e = errors[error];
170
+ const msg = typeof e === "function" ? e.apply(null, args) : e;
171
+ throw new Error(`[Immer] ${msg}`);
172
+ }
173
+ throw new Error(
174
+ `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`
175
+ );
176
+ }
177
+ var getPrototypeOf = Object.getPrototypeOf;
178
+ function isDraft(value) {
179
+ return !!value && !!value[DRAFT_STATE];
180
+ }
181
+ function isDraftable(value) {
182
+ if (!value)
183
+ return false;
184
+ return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap(value) || isSet(value);
185
+ }
186
+ var objectCtorString = Object.prototype.constructor.toString();
187
+ function isPlainObject(value) {
188
+ if (!value || typeof value !== "object")
189
+ return false;
190
+ const proto = getPrototypeOf(value);
191
+ if (proto === null) {
192
+ return true;
193
+ }
194
+ const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
195
+ if (Ctor === Object)
196
+ return true;
197
+ return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString;
198
+ }
199
+ function each(obj, iter) {
200
+ if (getArchtype(obj) === 0) {
201
+ Reflect.ownKeys(obj).forEach((key) => {
202
+ iter(key, obj[key], obj);
203
+ });
204
+ } else {
205
+ obj.forEach((entry, index) => iter(index, entry, obj));
206
+ }
207
+ }
208
+ function getArchtype(thing) {
209
+ const state = thing[DRAFT_STATE];
210
+ return state ? state.type_ : Array.isArray(thing) ? 1 : isMap(thing) ? 2 : isSet(thing) ? 3 : 0;
211
+ }
212
+ function has(thing, prop) {
213
+ return getArchtype(thing) === 2 ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
214
+ }
215
+ function set(thing, propOrOldValue, value) {
216
+ const t = getArchtype(thing);
217
+ if (t === 2)
218
+ thing.set(propOrOldValue, value);
219
+ else if (t === 3) {
220
+ thing.add(value);
221
+ } else
222
+ thing[propOrOldValue] = value;
223
+ }
224
+ function is(x, y) {
225
+ if (x === y) {
226
+ return x !== 0 || 1 / x === 1 / y;
227
+ } else {
228
+ return x !== x && y !== y;
229
+ }
230
+ }
231
+ function isMap(target) {
232
+ return target instanceof Map;
233
+ }
234
+ function isSet(target) {
235
+ return target instanceof Set;
236
+ }
237
+ function latest(state) {
238
+ return state.copy_ || state.base_;
239
+ }
240
+ function shallowCopy(base, strict) {
241
+ if (isMap(base)) {
242
+ return new Map(base);
243
+ }
244
+ if (isSet(base)) {
245
+ return new Set(base);
246
+ }
247
+ if (Array.isArray(base))
248
+ return Array.prototype.slice.call(base);
249
+ const isPlain = isPlainObject(base);
250
+ if (strict === true || strict === "class_only" && !isPlain) {
251
+ const descriptors = Object.getOwnPropertyDescriptors(base);
252
+ delete descriptors[DRAFT_STATE];
253
+ let keys = Reflect.ownKeys(descriptors);
254
+ for (let i = 0; i < keys.length; i++) {
255
+ const key = keys[i];
256
+ const desc = descriptors[key];
257
+ if (desc.writable === false) {
258
+ desc.writable = true;
259
+ desc.configurable = true;
260
+ }
261
+ if (desc.get || desc.set)
262
+ descriptors[key] = {
263
+ configurable: true,
264
+ writable: true,
265
+ // could live with !!desc.set as well here...
266
+ enumerable: desc.enumerable,
267
+ value: base[key]
268
+ };
269
+ }
270
+ return Object.create(getPrototypeOf(base), descriptors);
271
+ } else {
272
+ const proto = getPrototypeOf(base);
273
+ if (proto !== null && isPlain) {
274
+ return { ...base };
275
+ }
276
+ const obj = Object.create(proto);
277
+ return Object.assign(obj, base);
278
+ }
279
+ }
280
+ function freeze(obj, deep = false) {
281
+ if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
282
+ return obj;
283
+ if (getArchtype(obj) > 1) {
284
+ obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
285
+ }
286
+ Object.freeze(obj);
287
+ if (deep)
288
+ Object.entries(obj).forEach(([key, value]) => freeze(value, true));
289
+ return obj;
290
+ }
291
+ function dontMutateFrozenCollections() {
292
+ die(2);
293
+ }
294
+ function isFrozen(obj) {
295
+ return Object.isFrozen(obj);
296
+ }
297
+ var plugins = {};
298
+ function getPlugin(pluginKey) {
299
+ const plugin = plugins[pluginKey];
300
+ if (!plugin) {
301
+ die(0, pluginKey);
302
+ }
303
+ return plugin;
304
+ }
305
+ var currentScope;
306
+ function getCurrentScope() {
307
+ return currentScope;
308
+ }
309
+ function createScope(parent_, immer_) {
310
+ return {
311
+ drafts_: [],
312
+ parent_,
313
+ immer_,
314
+ // Whenever the modified draft contains a draft from another scope, we
315
+ // need to prevent auto-freezing so the unowned draft can be finalized.
316
+ canAutoFreeze_: true,
317
+ unfinalizedDrafts_: 0
318
+ };
319
+ }
320
+ function usePatchesInScope(scope, patchListener) {
321
+ if (patchListener) {
322
+ getPlugin("Patches");
323
+ scope.patches_ = [];
324
+ scope.inversePatches_ = [];
325
+ scope.patchListener_ = patchListener;
326
+ }
327
+ }
328
+ function revokeScope(scope) {
329
+ leaveScope(scope);
330
+ scope.drafts_.forEach(revokeDraft);
331
+ scope.drafts_ = null;
332
+ }
333
+ function leaveScope(scope) {
334
+ if (scope === currentScope) {
335
+ currentScope = scope.parent_;
336
+ }
337
+ }
338
+ function enterScope(immer2) {
339
+ return currentScope = createScope(currentScope, immer2);
340
+ }
341
+ function revokeDraft(draft) {
342
+ const state = draft[DRAFT_STATE];
343
+ if (state.type_ === 0 || state.type_ === 1)
344
+ state.revoke_();
345
+ else
346
+ state.revoked_ = true;
347
+ }
348
+ function processResult(result, scope) {
349
+ scope.unfinalizedDrafts_ = scope.drafts_.length;
350
+ const baseDraft = scope.drafts_[0];
351
+ const isReplaced = result !== void 0 && result !== baseDraft;
352
+ if (isReplaced) {
353
+ if (baseDraft[DRAFT_STATE].modified_) {
354
+ revokeScope(scope);
355
+ die(4);
356
+ }
357
+ if (isDraftable(result)) {
358
+ result = finalize(scope, result);
359
+ if (!scope.parent_)
360
+ maybeFreeze(scope, result);
361
+ }
362
+ if (scope.patches_) {
363
+ getPlugin("Patches").generateReplacementPatches_(
364
+ baseDraft[DRAFT_STATE].base_,
365
+ result,
366
+ scope.patches_,
367
+ scope.inversePatches_
368
+ );
369
+ }
370
+ } else {
371
+ result = finalize(scope, baseDraft, []);
372
+ }
373
+ revokeScope(scope);
374
+ if (scope.patches_) {
375
+ scope.patchListener_(scope.patches_, scope.inversePatches_);
376
+ }
377
+ return result !== NOTHING ? result : void 0;
378
+ }
379
+ function finalize(rootScope, value, path) {
380
+ if (isFrozen(value))
381
+ return value;
382
+ const state = value[DRAFT_STATE];
383
+ if (!state) {
384
+ each(
385
+ value,
386
+ (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path)
387
+ );
388
+ return value;
389
+ }
390
+ if (state.scope_ !== rootScope)
391
+ return value;
392
+ if (!state.modified_) {
393
+ maybeFreeze(rootScope, state.base_, true);
394
+ return state.base_;
395
+ }
396
+ if (!state.finalized_) {
397
+ state.finalized_ = true;
398
+ state.scope_.unfinalizedDrafts_--;
399
+ const result = state.copy_;
400
+ let resultEach = result;
401
+ let isSet2 = false;
402
+ if (state.type_ === 3) {
403
+ resultEach = new Set(result);
404
+ result.clear();
405
+ isSet2 = true;
406
+ }
407
+ each(
408
+ resultEach,
409
+ (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2)
410
+ );
411
+ maybeFreeze(rootScope, result, false);
412
+ if (path && rootScope.patches_) {
413
+ getPlugin("Patches").generatePatches_(
414
+ state,
415
+ path,
416
+ rootScope.patches_,
417
+ rootScope.inversePatches_
418
+ );
419
+ }
420
+ }
421
+ return state.copy_;
422
+ }
423
+ function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {
424
+ if (process.env.NODE_ENV !== "production" && childValue === targetObject)
425
+ die(5);
426
+ if (isDraft(childValue)) {
427
+ const path = rootPath && parentState && parentState.type_ !== 3 && // Set objects are atomic since they have no keys.
428
+ !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;
429
+ const res = finalize(rootScope, childValue, path);
430
+ set(targetObject, prop, res);
431
+ if (isDraft(res)) {
432
+ rootScope.canAutoFreeze_ = false;
433
+ } else
434
+ return;
435
+ } else if (targetIsSet) {
436
+ targetObject.add(childValue);
437
+ }
438
+ if (isDraftable(childValue) && !isFrozen(childValue)) {
439
+ if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
440
+ return;
441
+ }
442
+ finalize(rootScope, childValue);
443
+ if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop))
444
+ maybeFreeze(rootScope, childValue);
445
+ }
446
+ }
447
+ function maybeFreeze(scope, value, deep = false) {
448
+ if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
449
+ freeze(value, deep);
450
+ }
451
+ }
452
+ function createProxyProxy(base, parent) {
453
+ const isArray = Array.isArray(base);
454
+ const state = {
455
+ type_: isArray ? 1 : 0,
456
+ // Track which produce call this is associated with.
457
+ scope_: parent ? parent.scope_ : getCurrentScope(),
458
+ // True for both shallow and deep changes.
459
+ modified_: false,
460
+ // Used during finalization.
461
+ finalized_: false,
462
+ // Track which properties have been assigned (true) or deleted (false).
463
+ assigned_: {},
464
+ // The parent draft state.
465
+ parent_: parent,
466
+ // The base state.
467
+ base_: base,
468
+ // The base proxy.
469
+ draft_: null,
470
+ // set below
471
+ // The base copy with any updated values.
472
+ copy_: null,
473
+ // Called by the `produce` function.
474
+ revoke_: null,
475
+ isManual_: false
476
+ };
477
+ let target = state;
478
+ let traps = objectTraps;
479
+ if (isArray) {
480
+ target = [state];
481
+ traps = arrayTraps;
482
+ }
483
+ const { revoke, proxy } = Proxy.revocable(target, traps);
484
+ state.draft_ = proxy;
485
+ state.revoke_ = revoke;
486
+ return proxy;
487
+ }
488
+ var objectTraps = {
489
+ get(state, prop) {
490
+ if (prop === DRAFT_STATE)
491
+ return state;
492
+ const source = latest(state);
493
+ if (!has(source, prop)) {
494
+ return readPropFromProto(state, source, prop);
495
+ }
496
+ const value = source[prop];
497
+ if (state.finalized_ || !isDraftable(value)) {
498
+ return value;
499
+ }
500
+ if (value === peek(state.base_, prop)) {
501
+ prepareCopy(state);
502
+ return state.copy_[prop] = createProxy(value, state);
503
+ }
504
+ return value;
505
+ },
506
+ has(state, prop) {
507
+ return prop in latest(state);
508
+ },
509
+ ownKeys(state) {
510
+ return Reflect.ownKeys(latest(state));
511
+ },
512
+ set(state, prop, value) {
513
+ const desc = getDescriptorFromProto(latest(state), prop);
514
+ if (desc?.set) {
515
+ desc.set.call(state.draft_, value);
516
+ return true;
517
+ }
518
+ if (!state.modified_) {
519
+ const current2 = peek(latest(state), prop);
520
+ const currentState = current2?.[DRAFT_STATE];
521
+ if (currentState && currentState.base_ === value) {
522
+ state.copy_[prop] = value;
523
+ state.assigned_[prop] = false;
524
+ return true;
525
+ }
526
+ if (is(value, current2) && (value !== void 0 || has(state.base_, prop)))
527
+ return true;
528
+ prepareCopy(state);
529
+ markChanged(state);
530
+ }
531
+ if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
532
+ (value !== void 0 || prop in state.copy_) || // special case: NaN
533
+ Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
534
+ return true;
535
+ state.copy_[prop] = value;
536
+ state.assigned_[prop] = true;
537
+ return true;
538
+ },
539
+ deleteProperty(state, prop) {
540
+ if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
541
+ state.assigned_[prop] = false;
542
+ prepareCopy(state);
543
+ markChanged(state);
544
+ } else {
545
+ delete state.assigned_[prop];
546
+ }
547
+ if (state.copy_) {
548
+ delete state.copy_[prop];
549
+ }
550
+ return true;
551
+ },
552
+ // Note: We never coerce `desc.value` into an Immer draft, because we can't make
553
+ // the same guarantee in ES5 mode.
554
+ getOwnPropertyDescriptor(state, prop) {
555
+ const owner = latest(state);
556
+ const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
557
+ if (!desc)
558
+ return desc;
559
+ return {
560
+ writable: true,
561
+ configurable: state.type_ !== 1 || prop !== "length",
562
+ enumerable: desc.enumerable,
563
+ value: owner[prop]
564
+ };
565
+ },
566
+ defineProperty() {
567
+ die(11);
568
+ },
569
+ getPrototypeOf(state) {
570
+ return getPrototypeOf(state.base_);
571
+ },
572
+ setPrototypeOf() {
573
+ die(12);
574
+ }
575
+ };
576
+ var arrayTraps = {};
577
+ each(objectTraps, (key, fn) => {
578
+ arrayTraps[key] = function() {
579
+ arguments[0] = arguments[0][0];
580
+ return fn.apply(this, arguments);
581
+ };
582
+ });
583
+ arrayTraps.deleteProperty = function(state, prop) {
584
+ if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop)))
585
+ die(13);
586
+ return arrayTraps.set.call(this, state, prop, void 0);
587
+ };
588
+ arrayTraps.set = function(state, prop, value) {
589
+ if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop)))
590
+ die(14);
591
+ return objectTraps.set.call(this, state[0], prop, value, state[0]);
592
+ };
593
+ function peek(draft, prop) {
594
+ const state = draft[DRAFT_STATE];
595
+ const source = state ? latest(state) : draft;
596
+ return source[prop];
597
+ }
598
+ function readPropFromProto(state, source, prop) {
599
+ const desc = getDescriptorFromProto(source, prop);
600
+ return desc ? `value` in desc ? desc.value : (
601
+ // This is a very special case, if the prop is a getter defined by the
602
+ // prototype, we should invoke it with the draft as context!
603
+ desc.get?.call(state.draft_)
604
+ ) : void 0;
605
+ }
606
+ function getDescriptorFromProto(source, prop) {
607
+ if (!(prop in source))
608
+ return void 0;
609
+ let proto = getPrototypeOf(source);
610
+ while (proto) {
611
+ const desc = Object.getOwnPropertyDescriptor(proto, prop);
612
+ if (desc)
613
+ return desc;
614
+ proto = getPrototypeOf(proto);
615
+ }
616
+ return void 0;
617
+ }
618
+ function markChanged(state) {
619
+ if (!state.modified_) {
620
+ state.modified_ = true;
621
+ if (state.parent_) {
622
+ markChanged(state.parent_);
623
+ }
624
+ }
625
+ }
626
+ function prepareCopy(state) {
627
+ if (!state.copy_) {
628
+ state.copy_ = shallowCopy(
629
+ state.base_,
630
+ state.scope_.immer_.useStrictShallowCopy_
631
+ );
632
+ }
633
+ }
634
+ var Immer2 = class {
635
+ constructor(config) {
636
+ this.autoFreeze_ = true;
637
+ this.useStrictShallowCopy_ = false;
638
+ this.produce = (base, recipe, patchListener) => {
639
+ if (typeof base === "function" && typeof recipe !== "function") {
640
+ const defaultBase = recipe;
641
+ recipe = base;
642
+ const self = this;
643
+ return function curriedProduce(base2 = defaultBase, ...args) {
644
+ return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
645
+ };
646
+ }
647
+ if (typeof recipe !== "function")
648
+ die(6);
649
+ if (patchListener !== void 0 && typeof patchListener !== "function")
650
+ die(7);
651
+ let result;
652
+ if (isDraftable(base)) {
653
+ const scope = enterScope(this);
654
+ const proxy = createProxy(base, void 0);
655
+ let hasError = true;
656
+ try {
657
+ result = recipe(proxy);
658
+ hasError = false;
659
+ } finally {
660
+ if (hasError)
661
+ revokeScope(scope);
662
+ else
663
+ leaveScope(scope);
664
+ }
665
+ usePatchesInScope(scope, patchListener);
666
+ return processResult(result, scope);
667
+ } else if (!base || typeof base !== "object") {
668
+ result = recipe(base);
669
+ if (result === void 0)
670
+ result = base;
671
+ if (result === NOTHING)
672
+ result = void 0;
673
+ if (this.autoFreeze_)
674
+ freeze(result, true);
675
+ if (patchListener) {
676
+ const p = [];
677
+ const ip = [];
678
+ getPlugin("Patches").generateReplacementPatches_(base, result, p, ip);
679
+ patchListener(p, ip);
680
+ }
681
+ return result;
682
+ } else
683
+ die(1, base);
684
+ };
685
+ this.produceWithPatches = (base, recipe) => {
686
+ if (typeof base === "function") {
687
+ return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
688
+ }
689
+ let patches, inversePatches;
690
+ const result = this.produce(base, recipe, (p, ip) => {
691
+ patches = p;
692
+ inversePatches = ip;
693
+ });
694
+ return [result, patches, inversePatches];
695
+ };
696
+ if (typeof config?.autoFreeze === "boolean")
697
+ this.setAutoFreeze(config.autoFreeze);
698
+ if (typeof config?.useStrictShallowCopy === "boolean")
699
+ this.setUseStrictShallowCopy(config.useStrictShallowCopy);
700
+ }
701
+ createDraft(base) {
702
+ if (!isDraftable(base))
703
+ die(8);
704
+ if (isDraft(base))
705
+ base = current(base);
706
+ const scope = enterScope(this);
707
+ const proxy = createProxy(base, void 0);
708
+ proxy[DRAFT_STATE].isManual_ = true;
709
+ leaveScope(scope);
710
+ return proxy;
711
+ }
712
+ finishDraft(draft, patchListener) {
713
+ const state = draft && draft[DRAFT_STATE];
714
+ if (!state || !state.isManual_)
715
+ die(9);
716
+ const { scope_: scope } = state;
717
+ usePatchesInScope(scope, patchListener);
718
+ return processResult(void 0, scope);
719
+ }
720
+ /**
721
+ * Pass true to automatically freeze all copies created by Immer.
722
+ *
723
+ * By default, auto-freezing is enabled.
724
+ */
725
+ setAutoFreeze(value) {
726
+ this.autoFreeze_ = value;
727
+ }
728
+ /**
729
+ * Pass true to enable strict shallow copy.
730
+ *
731
+ * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
732
+ */
733
+ setUseStrictShallowCopy(value) {
734
+ this.useStrictShallowCopy_ = value;
735
+ }
736
+ applyPatches(base, patches) {
737
+ let i;
738
+ for (i = patches.length - 1; i >= 0; i--) {
739
+ const patch = patches[i];
740
+ if (patch.path.length === 0 && patch.op === "replace") {
741
+ base = patch.value;
742
+ break;
743
+ }
744
+ }
745
+ if (i > -1) {
746
+ patches = patches.slice(i + 1);
747
+ }
748
+ const applyPatchesImpl = getPlugin("Patches").applyPatches_;
749
+ if (isDraft(base)) {
750
+ return applyPatchesImpl(base, patches);
751
+ }
752
+ return this.produce(
753
+ base,
754
+ (draft) => applyPatchesImpl(draft, patches)
755
+ );
756
+ }
757
+ };
758
+ function createProxy(value, parent) {
759
+ const draft = isMap(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent);
760
+ const scope = parent ? parent.scope_ : getCurrentScope();
761
+ scope.drafts_.push(draft);
762
+ return draft;
763
+ }
764
+ function current(value) {
765
+ if (!isDraft(value))
766
+ die(10, value);
767
+ return currentImpl(value);
768
+ }
769
+ function currentImpl(value) {
770
+ if (!isDraftable(value) || isFrozen(value))
771
+ return value;
772
+ const state = value[DRAFT_STATE];
773
+ let copy;
774
+ if (state) {
775
+ if (!state.modified_)
776
+ return state.base_;
777
+ state.finalized_ = true;
778
+ copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
779
+ } else {
780
+ copy = shallowCopy(value, true);
781
+ }
782
+ each(copy, (key, childValue) => {
783
+ set(copy, key, currentImpl(childValue));
784
+ });
785
+ if (state) {
786
+ state.finalized_ = false;
787
+ }
788
+ return copy;
789
+ }
790
+ var immer = new Immer2();
791
+ var produce = immer.produce;
792
+ var produceWithPatches = immer.produceWithPatches.bind(
793
+ immer
794
+ );
795
+ var setAutoFreeze = immer.setAutoFreeze.bind(immer);
796
+ var setUseStrictShallowCopy = immer.setUseStrictShallowCopy.bind(immer);
797
+ var applyPatches = immer.applyPatches.bind(immer);
798
+ var createDraft = immer.createDraft.bind(immer);
799
+ var finishDraft = immer.finishDraft.bind(immer);
800
+
801
+ // ../../node_modules/slate/dist/index.es.js
802
+ var Path = {
803
+ ancestors(path) {
804
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
805
+ var {
806
+ reverse = false
807
+ } = options;
808
+ var paths = Path.levels(path, options);
809
+ if (reverse) {
810
+ paths = paths.slice(1);
811
+ } else {
812
+ paths = paths.slice(0, -1);
813
+ }
814
+ return paths;
815
+ },
816
+ common(path, another) {
817
+ var common = [];
818
+ for (var i = 0; i < path.length && i < another.length; i++) {
819
+ var av = path[i];
820
+ var bv = another[i];
821
+ if (av !== bv) {
822
+ break;
823
+ }
824
+ common.push(av);
825
+ }
826
+ return common;
827
+ },
828
+ compare(path, another) {
829
+ var min = Math.min(path.length, another.length);
830
+ for (var i = 0; i < min; i++) {
831
+ if (path[i] < another[i]) return -1;
832
+ if (path[i] > another[i]) return 1;
833
+ }
834
+ return 0;
835
+ },
836
+ endsAfter(path, another) {
837
+ var i = path.length - 1;
838
+ var as = path.slice(0, i);
839
+ var bs = another.slice(0, i);
840
+ var av = path[i];
841
+ var bv = another[i];
842
+ return Path.equals(as, bs) && av > bv;
843
+ },
844
+ endsAt(path, another) {
845
+ var i = path.length;
846
+ var as = path.slice(0, i);
847
+ var bs = another.slice(0, i);
848
+ return Path.equals(as, bs);
849
+ },
850
+ endsBefore(path, another) {
851
+ var i = path.length - 1;
852
+ var as = path.slice(0, i);
853
+ var bs = another.slice(0, i);
854
+ var av = path[i];
855
+ var bv = another[i];
856
+ return Path.equals(as, bs) && av < bv;
857
+ },
858
+ equals(path, another) {
859
+ return path.length === another.length && path.every((n, i) => n === another[i]);
860
+ },
861
+ hasPrevious(path) {
862
+ return path[path.length - 1] > 0;
863
+ },
864
+ isAfter(path, another) {
865
+ return Path.compare(path, another) === 1;
866
+ },
867
+ isAncestor(path, another) {
868
+ return path.length < another.length && Path.compare(path, another) === 0;
869
+ },
870
+ isBefore(path, another) {
871
+ return Path.compare(path, another) === -1;
872
+ },
873
+ isChild(path, another) {
874
+ return path.length === another.length + 1 && Path.compare(path, another) === 0;
875
+ },
876
+ isCommon(path, another) {
877
+ return path.length <= another.length && Path.compare(path, another) === 0;
878
+ },
879
+ isDescendant(path, another) {
880
+ return path.length > another.length && Path.compare(path, another) === 0;
881
+ },
882
+ isParent(path, another) {
883
+ return path.length + 1 === another.length && Path.compare(path, another) === 0;
884
+ },
885
+ isPath(value) {
886
+ return Array.isArray(value) && (value.length === 0 || typeof value[0] === "number");
887
+ },
888
+ isSibling(path, another) {
889
+ if (path.length !== another.length) {
890
+ return false;
891
+ }
892
+ var as = path.slice(0, -1);
893
+ var bs = another.slice(0, -1);
894
+ var al = path[path.length - 1];
895
+ var bl = another[another.length - 1];
896
+ return al !== bl && Path.equals(as, bs);
897
+ },
898
+ levels(path) {
899
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
900
+ var {
901
+ reverse = false
902
+ } = options;
903
+ var list = [];
904
+ for (var i = 0; i <= path.length; i++) {
905
+ list.push(path.slice(0, i));
906
+ }
907
+ if (reverse) {
908
+ list.reverse();
909
+ }
910
+ return list;
911
+ },
912
+ next(path) {
913
+ if (path.length === 0) {
914
+ throw new Error("Cannot get the next path of a root path [".concat(path, "], because it has no next index."));
915
+ }
916
+ var last = path[path.length - 1];
917
+ return path.slice(0, -1).concat(last + 1);
918
+ },
919
+ operationCanTransformPath(operation) {
920
+ switch (operation.type) {
921
+ case "insert_node":
922
+ case "remove_node":
923
+ case "merge_node":
924
+ case "split_node":
925
+ case "move_node":
926
+ return true;
927
+ default:
928
+ return false;
929
+ }
930
+ },
931
+ parent(path) {
932
+ if (path.length === 0) {
933
+ throw new Error("Cannot get the parent path of the root path [".concat(path, "]."));
934
+ }
935
+ return path.slice(0, -1);
936
+ },
937
+ previous(path) {
938
+ if (path.length === 0) {
939
+ throw new Error("Cannot get the previous path of a root path [".concat(path, "], because it has no previous index."));
940
+ }
941
+ var last = path[path.length - 1];
942
+ if (last <= 0) {
943
+ throw new Error("Cannot get the previous path of a first child path [".concat(path, "] because it would result in a negative index."));
944
+ }
945
+ return path.slice(0, -1).concat(last - 1);
946
+ },
947
+ relative(path, ancestor) {
948
+ if (!Path.isAncestor(ancestor, path) && !Path.equals(path, ancestor)) {
949
+ throw new Error("Cannot get the relative path of [".concat(path, "] inside ancestor [").concat(ancestor, "], because it is not above or equal to the path."));
950
+ }
951
+ return path.slice(ancestor.length);
952
+ },
953
+ transform(path, operation) {
954
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
955
+ if (!path) return null;
956
+ var p = [...path];
957
+ var {
958
+ affinity = "forward"
959
+ } = options;
960
+ if (path.length === 0) {
961
+ return p;
962
+ }
963
+ switch (operation.type) {
964
+ case "insert_node": {
965
+ var {
966
+ path: op
967
+ } = operation;
968
+ if (Path.equals(op, p) || Path.endsBefore(op, p) || Path.isAncestor(op, p)) {
969
+ p[op.length - 1] += 1;
970
+ }
971
+ break;
972
+ }
973
+ case "remove_node": {
974
+ var {
975
+ path: _op
976
+ } = operation;
977
+ if (Path.equals(_op, p) || Path.isAncestor(_op, p)) {
978
+ return null;
979
+ } else if (Path.endsBefore(_op, p)) {
980
+ p[_op.length - 1] -= 1;
981
+ }
982
+ break;
983
+ }
984
+ case "merge_node": {
985
+ var {
986
+ path: _op2,
987
+ position
988
+ } = operation;
989
+ if (Path.equals(_op2, p) || Path.endsBefore(_op2, p)) {
990
+ p[_op2.length - 1] -= 1;
991
+ } else if (Path.isAncestor(_op2, p)) {
992
+ p[_op2.length - 1] -= 1;
993
+ p[_op2.length] += position;
994
+ }
995
+ break;
996
+ }
997
+ case "split_node": {
998
+ var {
999
+ path: _op3,
1000
+ position: _position
1001
+ } = operation;
1002
+ if (Path.equals(_op3, p)) {
1003
+ if (affinity === "forward") {
1004
+ p[p.length - 1] += 1;
1005
+ } else if (affinity === "backward") ;
1006
+ else {
1007
+ return null;
1008
+ }
1009
+ } else if (Path.endsBefore(_op3, p)) {
1010
+ p[_op3.length - 1] += 1;
1011
+ } else if (Path.isAncestor(_op3, p) && path[_op3.length] >= _position) {
1012
+ p[_op3.length - 1] += 1;
1013
+ p[_op3.length] -= _position;
1014
+ }
1015
+ break;
1016
+ }
1017
+ case "move_node": {
1018
+ var {
1019
+ path: _op4,
1020
+ newPath: onp
1021
+ } = operation;
1022
+ if (Path.equals(_op4, onp)) {
1023
+ return p;
1024
+ }
1025
+ if (Path.isAncestor(_op4, p) || Path.equals(_op4, p)) {
1026
+ var copy = onp.slice();
1027
+ if (Path.endsBefore(_op4, onp) && _op4.length < onp.length) {
1028
+ copy[_op4.length - 1] -= 1;
1029
+ }
1030
+ return copy.concat(p.slice(_op4.length));
1031
+ } else if (Path.isSibling(_op4, onp) && (Path.isAncestor(onp, p) || Path.equals(onp, p))) {
1032
+ if (Path.endsBefore(_op4, p)) {
1033
+ p[_op4.length - 1] -= 1;
1034
+ } else {
1035
+ p[_op4.length - 1] += 1;
1036
+ }
1037
+ } else if (Path.endsBefore(onp, p) || Path.equals(onp, p) || Path.isAncestor(onp, p)) {
1038
+ if (Path.endsBefore(_op4, p)) {
1039
+ p[_op4.length - 1] -= 1;
1040
+ }
1041
+ p[onp.length - 1] += 1;
1042
+ } else if (Path.endsBefore(_op4, p)) {
1043
+ if (Path.equals(onp, p)) {
1044
+ p[onp.length - 1] += 1;
1045
+ }
1046
+ p[_op4.length - 1] -= 1;
1047
+ }
1048
+ break;
1049
+ }
1050
+ }
1051
+ return p;
1052
+ }
1053
+ };
1054
+ function _typeof(o) {
1055
+ "@babel/helpers - typeof";
1056
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
1057
+ return typeof o2;
1058
+ } : function(o2) {
1059
+ return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
1060
+ }, _typeof(o);
1061
+ }
1062
+ function _toPrimitive(input, hint) {
1063
+ if (_typeof(input) !== "object" || input === null) return input;
1064
+ var prim = input[Symbol.toPrimitive];
1065
+ if (prim !== void 0) {
1066
+ var res = prim.call(input, hint || "default");
1067
+ if (_typeof(res) !== "object") return res;
1068
+ throw new TypeError("@@toPrimitive must return a primitive value.");
1069
+ }
1070
+ return (hint === "string" ? String : Number)(input);
1071
+ }
1072
+ function _toPropertyKey(arg) {
1073
+ var key = _toPrimitive(arg, "string");
1074
+ return _typeof(key) === "symbol" ? key : String(key);
1075
+ }
1076
+ function _defineProperty(obj, key, value) {
1077
+ key = _toPropertyKey(key);
1078
+ if (key in obj) {
1079
+ Object.defineProperty(obj, key, {
1080
+ value,
1081
+ enumerable: true,
1082
+ configurable: true,
1083
+ writable: true
1084
+ });
1085
+ } else {
1086
+ obj[key] = value;
1087
+ }
1088
+ return obj;
1089
+ }
1090
+ function ownKeys$e(e, r) {
1091
+ var t = Object.keys(e);
1092
+ if (Object.getOwnPropertySymbols) {
1093
+ var o = Object.getOwnPropertySymbols(e);
1094
+ r && (o = o.filter(function(r2) {
1095
+ return Object.getOwnPropertyDescriptor(e, r2).enumerable;
1096
+ })), t.push.apply(t, o);
1097
+ }
1098
+ return t;
1099
+ }
1100
+ function _objectSpread$e(e) {
1101
+ for (var r = 1; r < arguments.length; r++) {
1102
+ var t = null != arguments[r] ? arguments[r] : {};
1103
+ r % 2 ? ownKeys$e(Object(t), true).forEach(function(r2) {
1104
+ _defineProperty(e, r2, t[r2]);
1105
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$e(Object(t)).forEach(function(r2) {
1106
+ Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
1107
+ });
1108
+ }
1109
+ return e;
1110
+ }
1111
+ var insertChildren = function insertChildren2(xs, index) {
1112
+ for (var _len = arguments.length, newValues = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
1113
+ newValues[_key - 2] = arguments[_key];
1114
+ }
1115
+ return [...xs.slice(0, index), ...newValues, ...xs.slice(index)];
1116
+ };
1117
+ var replaceChildren = function replaceChildren2(xs, index, removeCount) {
1118
+ for (var _len2 = arguments.length, newValues = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) {
1119
+ newValues[_key2 - 3] = arguments[_key2];
1120
+ }
1121
+ return [...xs.slice(0, index), ...newValues, ...xs.slice(index + removeCount)];
1122
+ };
1123
+ var removeChildren = replaceChildren;
1124
+ var modifyDescendant = (editor, path, f) => {
1125
+ if (path.length === 0) {
1126
+ throw new Error("Cannot modify the editor");
1127
+ }
1128
+ var node = Node.get(editor, path);
1129
+ var slicedPath = path.slice();
1130
+ var modifiedNode = f(node);
1131
+ while (slicedPath.length > 1) {
1132
+ var _index = slicedPath.pop();
1133
+ var ancestorNode = Node.get(editor, slicedPath);
1134
+ modifiedNode = _objectSpread$e(_objectSpread$e({}, ancestorNode), {}, {
1135
+ children: replaceChildren(ancestorNode.children, _index, 1, modifiedNode)
1136
+ });
1137
+ }
1138
+ var index = slicedPath.pop();
1139
+ editor.children = replaceChildren(editor.children, index, 1, modifiedNode);
1140
+ };
1141
+ var modifyChildren = (editor, path, f) => {
1142
+ if (path.length === 0) {
1143
+ editor.children = f(editor.children);
1144
+ } else {
1145
+ modifyDescendant(editor, path, (node) => {
1146
+ if (Text.isText(node)) {
1147
+ throw new Error("Cannot get the element at path [".concat(path, "] because it refers to a leaf node: ").concat(Scrubber.stringify(node)));
1148
+ }
1149
+ return _objectSpread$e(_objectSpread$e({}, node), {}, {
1150
+ children: f(node.children)
1151
+ });
1152
+ });
1153
+ }
1154
+ };
1155
+ var modifyLeaf = (editor, path, f) => modifyDescendant(editor, path, (node) => {
1156
+ if (!Text.isText(node)) {
1157
+ throw new Error("Cannot get the leaf node at path [".concat(path, "] because it refers to a non-leaf node: ").concat(Scrubber.stringify(node)));
1158
+ }
1159
+ return f(node);
1160
+ });
1161
+ var GeneralTransforms = {
1162
+ transform(editor, op) {
1163
+ var transformSelection = false;
1164
+ switch (op.type) {
1165
+ case "insert_node": {
1166
+ var {
1167
+ path,
1168
+ node
1169
+ } = op;
1170
+ modifyChildren(editor, Path.parent(path), (children) => {
1171
+ var index2 = path[path.length - 1];
1172
+ if (index2 > children.length) {
1173
+ throw new Error('Cannot apply an "insert_node" operation at path ['.concat(path, "] because the destination is past the end of the node."));
1174
+ }
1175
+ return insertChildren(children, index2, node);
1176
+ });
1177
+ transformSelection = true;
1178
+ break;
1179
+ }
1180
+ case "insert_text": {
1181
+ var {
1182
+ path: _path,
1183
+ offset,
1184
+ text
1185
+ } = op;
1186
+ if (text.length === 0) break;
1187
+ modifyLeaf(editor, _path, (node2) => {
1188
+ var before = node2.text.slice(0, offset);
1189
+ var after = node2.text.slice(offset);
1190
+ return _objectSpread$e(_objectSpread$e({}, node2), {}, {
1191
+ text: before + text + after
1192
+ });
1193
+ });
1194
+ transformSelection = true;
1195
+ break;
1196
+ }
1197
+ case "merge_node": {
1198
+ var {
1199
+ path: _path2
1200
+ } = op;
1201
+ var index = _path2[_path2.length - 1];
1202
+ var prevPath = Path.previous(_path2);
1203
+ var prevIndex = prevPath[prevPath.length - 1];
1204
+ modifyChildren(editor, Path.parent(_path2), (children) => {
1205
+ var node2 = children[index];
1206
+ var prev2 = children[prevIndex];
1207
+ var newNode;
1208
+ if (Text.isText(node2) && Text.isText(prev2)) {
1209
+ newNode = _objectSpread$e(_objectSpread$e({}, prev2), {}, {
1210
+ text: prev2.text + node2.text
1211
+ });
1212
+ } else if (!Text.isText(node2) && !Text.isText(prev2)) {
1213
+ newNode = _objectSpread$e(_objectSpread$e({}, prev2), {}, {
1214
+ children: prev2.children.concat(node2.children)
1215
+ });
1216
+ } else {
1217
+ throw new Error('Cannot apply a "merge_node" operation at path ['.concat(_path2, "] to nodes of different interfaces: ").concat(Scrubber.stringify(node2), " ").concat(Scrubber.stringify(prev2)));
1218
+ }
1219
+ return replaceChildren(children, prevIndex, 2, newNode);
1220
+ });
1221
+ transformSelection = true;
1222
+ break;
1223
+ }
1224
+ case "move_node": {
1225
+ var {
1226
+ path: _path3,
1227
+ newPath
1228
+ } = op;
1229
+ var _index2 = _path3[_path3.length - 1];
1230
+ if (Path.isAncestor(_path3, newPath)) {
1231
+ throw new Error("Cannot move a path [".concat(_path3, "] to new path [").concat(newPath, "] because the destination is inside itself."));
1232
+ }
1233
+ var _node = Node.get(editor, _path3);
1234
+ modifyChildren(editor, Path.parent(_path3), (children) => removeChildren(children, _index2, 1));
1235
+ var truePath = Path.transform(_path3, op);
1236
+ var newIndex = truePath[truePath.length - 1];
1237
+ modifyChildren(editor, Path.parent(truePath), (children) => insertChildren(children, newIndex, _node));
1238
+ transformSelection = true;
1239
+ break;
1240
+ }
1241
+ case "remove_node": {
1242
+ var {
1243
+ path: _path4
1244
+ } = op;
1245
+ var _index3 = _path4[_path4.length - 1];
1246
+ modifyChildren(editor, Path.parent(_path4), (children) => removeChildren(children, _index3, 1));
1247
+ if (editor.selection) {
1248
+ var selection = _objectSpread$e({}, editor.selection);
1249
+ for (var [point, key] of Range.points(selection)) {
1250
+ var result = Point.transform(point, op);
1251
+ if (selection != null && result != null) {
1252
+ selection[key] = result;
1253
+ } else {
1254
+ var prev = void 0;
1255
+ var next = void 0;
1256
+ for (var [n, p] of Node.texts(editor)) {
1257
+ if (Path.compare(p, _path4) === -1) {
1258
+ prev = [n, p];
1259
+ } else {
1260
+ next = [n, p];
1261
+ break;
1262
+ }
1263
+ }
1264
+ var preferNext = false;
1265
+ if (prev && next) {
1266
+ if (Path.isSibling(prev[1], _path4)) {
1267
+ preferNext = false;
1268
+ } else if (Path.equals(next[1], _path4)) {
1269
+ preferNext = true;
1270
+ } else {
1271
+ preferNext = Path.common(prev[1], _path4).length < Path.common(next[1], _path4).length;
1272
+ }
1273
+ }
1274
+ if (prev && !preferNext) {
1275
+ selection[key] = {
1276
+ path: prev[1],
1277
+ offset: prev[0].text.length
1278
+ };
1279
+ } else if (next) {
1280
+ selection[key] = {
1281
+ path: next[1],
1282
+ offset: 0
1283
+ };
1284
+ } else {
1285
+ selection = null;
1286
+ }
1287
+ }
1288
+ }
1289
+ if (!selection || !Range.equals(selection, editor.selection)) {
1290
+ editor.selection = selection;
1291
+ }
1292
+ }
1293
+ break;
1294
+ }
1295
+ case "remove_text": {
1296
+ var {
1297
+ path: _path5,
1298
+ offset: _offset,
1299
+ text: _text
1300
+ } = op;
1301
+ if (_text.length === 0) break;
1302
+ modifyLeaf(editor, _path5, (node2) => {
1303
+ var before = node2.text.slice(0, _offset);
1304
+ var after = node2.text.slice(_offset + _text.length);
1305
+ return _objectSpread$e(_objectSpread$e({}, node2), {}, {
1306
+ text: before + after
1307
+ });
1308
+ });
1309
+ transformSelection = true;
1310
+ break;
1311
+ }
1312
+ case "set_node": {
1313
+ var {
1314
+ path: _path6,
1315
+ properties,
1316
+ newProperties
1317
+ } = op;
1318
+ if (_path6.length === 0) {
1319
+ throw new Error("Cannot set properties on the root node!");
1320
+ }
1321
+ modifyDescendant(editor, _path6, (node2) => {
1322
+ var newNode = _objectSpread$e({}, node2);
1323
+ for (var _key3 in newProperties) {
1324
+ if (_key3 === "children" || _key3 === "text") {
1325
+ throw new Error('Cannot set the "'.concat(_key3, '" property of nodes!'));
1326
+ }
1327
+ var value2 = newProperties[_key3];
1328
+ if (value2 == null) {
1329
+ delete newNode[_key3];
1330
+ } else {
1331
+ newNode[_key3] = value2;
1332
+ }
1333
+ }
1334
+ for (var _key4 in properties) {
1335
+ if (!newProperties.hasOwnProperty(_key4)) {
1336
+ delete newNode[_key4];
1337
+ }
1338
+ }
1339
+ return newNode;
1340
+ });
1341
+ break;
1342
+ }
1343
+ case "set_selection": {
1344
+ var {
1345
+ newProperties: _newProperties
1346
+ } = op;
1347
+ if (_newProperties == null) {
1348
+ editor.selection = null;
1349
+ break;
1350
+ }
1351
+ if (editor.selection == null) {
1352
+ if (!Range.isRange(_newProperties)) {
1353
+ throw new Error('Cannot apply an incomplete "set_selection" operation properties '.concat(Scrubber.stringify(_newProperties), " when there is no current selection."));
1354
+ }
1355
+ editor.selection = _objectSpread$e({}, _newProperties);
1356
+ break;
1357
+ }
1358
+ var _selection = _objectSpread$e({}, editor.selection);
1359
+ for (var _key5 in _newProperties) {
1360
+ var value = _newProperties[_key5];
1361
+ if (value == null) {
1362
+ if (_key5 === "anchor" || _key5 === "focus") {
1363
+ throw new Error('Cannot remove the "'.concat(_key5, '" selection property'));
1364
+ }
1365
+ delete _selection[_key5];
1366
+ } else {
1367
+ _selection[_key5] = value;
1368
+ }
1369
+ }
1370
+ editor.selection = _selection;
1371
+ break;
1372
+ }
1373
+ case "split_node": {
1374
+ var {
1375
+ path: _path7,
1376
+ position,
1377
+ properties: _properties
1378
+ } = op;
1379
+ var _index4 = _path7[_path7.length - 1];
1380
+ if (_path7.length === 0) {
1381
+ throw new Error('Cannot apply a "split_node" operation at path ['.concat(_path7, "] because the root node cannot be split."));
1382
+ }
1383
+ modifyChildren(editor, Path.parent(_path7), (children) => {
1384
+ var node2 = children[_index4];
1385
+ var newNode;
1386
+ var nextNode;
1387
+ if (Text.isText(node2)) {
1388
+ var before = node2.text.slice(0, position);
1389
+ var after = node2.text.slice(position);
1390
+ newNode = _objectSpread$e(_objectSpread$e({}, node2), {}, {
1391
+ text: before
1392
+ });
1393
+ nextNode = _objectSpread$e(_objectSpread$e({}, _properties), {}, {
1394
+ text: after
1395
+ });
1396
+ } else {
1397
+ var _before = node2.children.slice(0, position);
1398
+ var _after = node2.children.slice(position);
1399
+ newNode = _objectSpread$e(_objectSpread$e({}, node2), {}, {
1400
+ children: _before
1401
+ });
1402
+ nextNode = _objectSpread$e(_objectSpread$e({}, _properties), {}, {
1403
+ children: _after
1404
+ });
1405
+ }
1406
+ return replaceChildren(children, _index4, 1, newNode, nextNode);
1407
+ });
1408
+ transformSelection = true;
1409
+ break;
1410
+ }
1411
+ }
1412
+ if (transformSelection && editor.selection) {
1413
+ var _selection2 = _objectSpread$e({}, editor.selection);
1414
+ for (var [_point, _key6] of Range.points(_selection2)) {
1415
+ _selection2[_key6] = Point.transform(_point, op);
1416
+ }
1417
+ if (!Range.equals(_selection2, editor.selection)) {
1418
+ editor.selection = _selection2;
1419
+ }
1420
+ }
1421
+ }
1422
+ };
1423
+ var NodeTransforms = {
1424
+ insertNodes(editor, nodes, options) {
1425
+ editor.insertNodes(nodes, options);
1426
+ },
1427
+ liftNodes(editor, options) {
1428
+ editor.liftNodes(options);
1429
+ },
1430
+ mergeNodes(editor, options) {
1431
+ editor.mergeNodes(options);
1432
+ },
1433
+ moveNodes(editor, options) {
1434
+ editor.moveNodes(options);
1435
+ },
1436
+ removeNodes(editor, options) {
1437
+ editor.removeNodes(options);
1438
+ },
1439
+ setNodes(editor, props, options) {
1440
+ editor.setNodes(props, options);
1441
+ },
1442
+ splitNodes(editor, options) {
1443
+ editor.splitNodes(options);
1444
+ },
1445
+ unsetNodes(editor, props, options) {
1446
+ editor.unsetNodes(props, options);
1447
+ },
1448
+ unwrapNodes(editor, options) {
1449
+ editor.unwrapNodes(options);
1450
+ },
1451
+ wrapNodes(editor, element, options) {
1452
+ editor.wrapNodes(element, options);
1453
+ }
1454
+ };
1455
+ var SelectionTransforms = {
1456
+ collapse(editor, options) {
1457
+ editor.collapse(options);
1458
+ },
1459
+ deselect(editor) {
1460
+ editor.deselect();
1461
+ },
1462
+ move(editor, options) {
1463
+ editor.move(options);
1464
+ },
1465
+ select(editor, target) {
1466
+ editor.select(target);
1467
+ },
1468
+ setPoint(editor, props, options) {
1469
+ editor.setPoint(props, options);
1470
+ },
1471
+ setSelection(editor, props) {
1472
+ editor.setSelection(props);
1473
+ }
1474
+ };
1475
+ var isObject = (value) => typeof value === "object" && value !== null;
1476
+ var isDeepEqual = (node, another) => {
1477
+ for (var key in node) {
1478
+ var a = node[key];
1479
+ var b = another[key];
1480
+ if (Array.isArray(a) && Array.isArray(b)) {
1481
+ if (a.length !== b.length) return false;
1482
+ for (var i = 0; i < a.length; i++) {
1483
+ if (a[i] !== b[i]) return false;
1484
+ }
1485
+ } else if (isObject(a) && isObject(b)) {
1486
+ if (!isDeepEqual(a, b)) return false;
1487
+ } else if (a !== b) {
1488
+ return false;
1489
+ }
1490
+ }
1491
+ for (var _key in another) {
1492
+ if (node[_key] === void 0 && another[_key] !== void 0) {
1493
+ return false;
1494
+ }
1495
+ }
1496
+ return true;
1497
+ };
1498
+ function _objectWithoutPropertiesLoose(source, excluded) {
1499
+ if (source == null) return {};
1500
+ var target = {};
1501
+ var sourceKeys = Object.keys(source);
1502
+ var key, i;
1503
+ for (i = 0; i < sourceKeys.length; i++) {
1504
+ key = sourceKeys[i];
1505
+ if (excluded.indexOf(key) >= 0) continue;
1506
+ target[key] = source[key];
1507
+ }
1508
+ return target;
1509
+ }
1510
+ function _objectWithoutProperties(source, excluded) {
1511
+ if (source == null) return {};
1512
+ var target = _objectWithoutPropertiesLoose(source, excluded);
1513
+ var key, i;
1514
+ if (Object.getOwnPropertySymbols) {
1515
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
1516
+ for (i = 0; i < sourceSymbolKeys.length; i++) {
1517
+ key = sourceSymbolKeys[i];
1518
+ if (excluded.indexOf(key) >= 0) continue;
1519
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
1520
+ target[key] = source[key];
1521
+ }
1522
+ }
1523
+ return target;
1524
+ }
1525
+ var _excluded$4 = ["anchor", "focus"];
1526
+ function ownKeys$d(e, r) {
1527
+ var t = Object.keys(e);
1528
+ if (Object.getOwnPropertySymbols) {
1529
+ var o = Object.getOwnPropertySymbols(e);
1530
+ r && (o = o.filter(function(r2) {
1531
+ return Object.getOwnPropertyDescriptor(e, r2).enumerable;
1532
+ })), t.push.apply(t, o);
1533
+ }
1534
+ return t;
1535
+ }
1536
+ function _objectSpread$d(e) {
1537
+ for (var r = 1; r < arguments.length; r++) {
1538
+ var t = null != arguments[r] ? arguments[r] : {};
1539
+ r % 2 ? ownKeys$d(Object(t), true).forEach(function(r2) {
1540
+ _defineProperty(e, r2, t[r2]);
1541
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$d(Object(t)).forEach(function(r2) {
1542
+ Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
1543
+ });
1544
+ }
1545
+ return e;
1546
+ }
1547
+ var Range = {
1548
+ edges(range) {
1549
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1550
+ var {
1551
+ reverse = false
1552
+ } = options;
1553
+ var {
1554
+ anchor,
1555
+ focus
1556
+ } = range;
1557
+ return Range.isBackward(range) === reverse ? [anchor, focus] : [focus, anchor];
1558
+ },
1559
+ end(range) {
1560
+ var [, end] = Range.edges(range);
1561
+ return end;
1562
+ },
1563
+ equals(range, another) {
1564
+ return Point.equals(range.anchor, another.anchor) && Point.equals(range.focus, another.focus);
1565
+ },
1566
+ surrounds(range, target) {
1567
+ var intersectionRange = Range.intersection(range, target);
1568
+ if (!intersectionRange) {
1569
+ return false;
1570
+ }
1571
+ return Range.equals(intersectionRange, target);
1572
+ },
1573
+ includes(range, target) {
1574
+ if (Range.isRange(target)) {
1575
+ if (Range.includes(range, target.anchor) || Range.includes(range, target.focus)) {
1576
+ return true;
1577
+ }
1578
+ var [rs, re] = Range.edges(range);
1579
+ var [ts, te] = Range.edges(target);
1580
+ return Point.isBefore(rs, ts) && Point.isAfter(re, te);
1581
+ }
1582
+ var [start, end] = Range.edges(range);
1583
+ var isAfterStart = false;
1584
+ var isBeforeEnd = false;
1585
+ if (Point.isPoint(target)) {
1586
+ isAfterStart = Point.compare(target, start) >= 0;
1587
+ isBeforeEnd = Point.compare(target, end) <= 0;
1588
+ } else {
1589
+ isAfterStart = Path.compare(target, start.path) >= 0;
1590
+ isBeforeEnd = Path.compare(target, end.path) <= 0;
1591
+ }
1592
+ return isAfterStart && isBeforeEnd;
1593
+ },
1594
+ intersection(range, another) {
1595
+ var rest = _objectWithoutProperties(range, _excluded$4);
1596
+ var [s1, e1] = Range.edges(range);
1597
+ var [s2, e2] = Range.edges(another);
1598
+ var start = Point.isBefore(s1, s2) ? s2 : s1;
1599
+ var end = Point.isBefore(e1, e2) ? e1 : e2;
1600
+ if (Point.isBefore(end, start)) {
1601
+ return null;
1602
+ } else {
1603
+ return _objectSpread$d({
1604
+ anchor: start,
1605
+ focus: end
1606
+ }, rest);
1607
+ }
1608
+ },
1609
+ isBackward(range) {
1610
+ var {
1611
+ anchor,
1612
+ focus
1613
+ } = range;
1614
+ return Point.isAfter(anchor, focus);
1615
+ },
1616
+ isCollapsed(range) {
1617
+ var {
1618
+ anchor,
1619
+ focus
1620
+ } = range;
1621
+ return Point.equals(anchor, focus);
1622
+ },
1623
+ isExpanded(range) {
1624
+ return !Range.isCollapsed(range);
1625
+ },
1626
+ isForward(range) {
1627
+ return !Range.isBackward(range);
1628
+ },
1629
+ isRange(value) {
1630
+ return isObject(value) && Point.isPoint(value.anchor) && Point.isPoint(value.focus);
1631
+ },
1632
+ *points(range) {
1633
+ yield [range.anchor, "anchor"];
1634
+ yield [range.focus, "focus"];
1635
+ },
1636
+ start(range) {
1637
+ var [start] = Range.edges(range);
1638
+ return start;
1639
+ },
1640
+ transform(range, op) {
1641
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1642
+ if (range === null) {
1643
+ return null;
1644
+ }
1645
+ var {
1646
+ affinity = "inward"
1647
+ } = options;
1648
+ var affinityAnchor;
1649
+ var affinityFocus;
1650
+ if (affinity === "inward") {
1651
+ var isCollapsed = Range.isCollapsed(range);
1652
+ if (Range.isForward(range)) {
1653
+ affinityAnchor = "forward";
1654
+ affinityFocus = isCollapsed ? affinityAnchor : "backward";
1655
+ } else {
1656
+ affinityAnchor = "backward";
1657
+ affinityFocus = isCollapsed ? affinityAnchor : "forward";
1658
+ }
1659
+ } else if (affinity === "outward") {
1660
+ if (Range.isForward(range)) {
1661
+ affinityAnchor = "backward";
1662
+ affinityFocus = "forward";
1663
+ } else {
1664
+ affinityAnchor = "forward";
1665
+ affinityFocus = "backward";
1666
+ }
1667
+ } else {
1668
+ affinityAnchor = affinity;
1669
+ affinityFocus = affinity;
1670
+ }
1671
+ var anchor = Point.transform(range.anchor, op, {
1672
+ affinity: affinityAnchor
1673
+ });
1674
+ var focus = Point.transform(range.focus, op, {
1675
+ affinity: affinityFocus
1676
+ });
1677
+ if (!anchor || !focus) {
1678
+ return null;
1679
+ }
1680
+ return {
1681
+ anchor,
1682
+ focus
1683
+ };
1684
+ }
1685
+ };
1686
+ var isElement = function isElement2(value) {
1687
+ var {
1688
+ deep = false
1689
+ } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1690
+ if (!isObject(value)) return false;
1691
+ var isEditor3 = typeof value.apply === "function";
1692
+ if (isEditor3) return false;
1693
+ var isChildrenValid = deep ? Node.isNodeList(value.children) : Array.isArray(value.children);
1694
+ return isChildrenValid;
1695
+ };
1696
+ var Element = {
1697
+ isAncestor(value) {
1698
+ var {
1699
+ deep = false
1700
+ } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1701
+ return isObject(value) && Node.isNodeList(value.children, {
1702
+ deep
1703
+ });
1704
+ },
1705
+ isElement,
1706
+ isElementList(value) {
1707
+ var {
1708
+ deep = false
1709
+ } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1710
+ return Array.isArray(value) && value.every((val) => Element.isElement(val, {
1711
+ deep
1712
+ }));
1713
+ },
1714
+ isElementProps(props) {
1715
+ return props.children !== void 0;
1716
+ },
1717
+ isElementType: function isElementType(value, elementVal) {
1718
+ var elementKey = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "type";
1719
+ return isElement(value) && value[elementKey] === elementVal;
1720
+ },
1721
+ matches(element, props) {
1722
+ for (var key in props) {
1723
+ if (key === "children") {
1724
+ continue;
1725
+ }
1726
+ if (element[key] !== props[key]) {
1727
+ return false;
1728
+ }
1729
+ }
1730
+ return true;
1731
+ }
1732
+ };
1733
+ var _excluded$3 = ["children"];
1734
+ var _excluded2$3 = ["text"];
1735
+ var Node = {
1736
+ ancestor(root, path) {
1737
+ var node = Node.get(root, path);
1738
+ if (Text.isText(node)) {
1739
+ throw new Error("Cannot get the ancestor node at path [".concat(path, "] because it refers to a text node instead: ").concat(Scrubber.stringify(node)));
1740
+ }
1741
+ return node;
1742
+ },
1743
+ ancestors(root, path) {
1744
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1745
+ return function* () {
1746
+ for (var p of Path.ancestors(path, options)) {
1747
+ var n = Node.ancestor(root, p);
1748
+ var entry = [n, p];
1749
+ yield entry;
1750
+ }
1751
+ }();
1752
+ },
1753
+ child(root, index) {
1754
+ if (Text.isText(root)) {
1755
+ throw new Error("Cannot get the child of a text node: ".concat(Scrubber.stringify(root)));
1756
+ }
1757
+ var c = root.children[index];
1758
+ if (c == null) {
1759
+ throw new Error("Cannot get child at index `".concat(index, "` in node: ").concat(Scrubber.stringify(root)));
1760
+ }
1761
+ return c;
1762
+ },
1763
+ children(root, path) {
1764
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1765
+ return function* () {
1766
+ var {
1767
+ reverse = false
1768
+ } = options;
1769
+ var ancestor = Node.ancestor(root, path);
1770
+ var {
1771
+ children
1772
+ } = ancestor;
1773
+ var index = reverse ? children.length - 1 : 0;
1774
+ while (reverse ? index >= 0 : index < children.length) {
1775
+ var child = Node.child(ancestor, index);
1776
+ var childPath = path.concat(index);
1777
+ yield [child, childPath];
1778
+ index = reverse ? index - 1 : index + 1;
1779
+ }
1780
+ }();
1781
+ },
1782
+ common(root, path, another) {
1783
+ var p = Path.common(path, another);
1784
+ var n = Node.get(root, p);
1785
+ return [n, p];
1786
+ },
1787
+ descendant(root, path) {
1788
+ var node = Node.get(root, path);
1789
+ if (Editor.isEditor(node)) {
1790
+ throw new Error("Cannot get the descendant node at path [".concat(path, "] because it refers to the root editor node instead: ").concat(Scrubber.stringify(node)));
1791
+ }
1792
+ return node;
1793
+ },
1794
+ descendants(root) {
1795
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1796
+ return function* () {
1797
+ for (var [node, path] of Node.nodes(root, options)) {
1798
+ if (path.length !== 0) {
1799
+ yield [node, path];
1800
+ }
1801
+ }
1802
+ }();
1803
+ },
1804
+ elements(root) {
1805
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1806
+ return function* () {
1807
+ for (var [node, path] of Node.nodes(root, options)) {
1808
+ if (Element.isElement(node)) {
1809
+ yield [node, path];
1810
+ }
1811
+ }
1812
+ }();
1813
+ },
1814
+ extractProps(node) {
1815
+ if (Element.isAncestor(node)) {
1816
+ var properties = _objectWithoutProperties(node, _excluded$3);
1817
+ return properties;
1818
+ } else {
1819
+ var properties = _objectWithoutProperties(node, _excluded2$3);
1820
+ return properties;
1821
+ }
1822
+ },
1823
+ first(root, path) {
1824
+ var p = path.slice();
1825
+ var n = Node.get(root, p);
1826
+ while (n) {
1827
+ if (Text.isText(n) || n.children.length === 0) {
1828
+ break;
1829
+ } else {
1830
+ n = n.children[0];
1831
+ p.push(0);
1832
+ }
1833
+ }
1834
+ return [n, p];
1835
+ },
1836
+ fragment(root, range) {
1837
+ var newRoot = produce({
1838
+ children: root.children
1839
+ }, (r) => {
1840
+ var [start, end] = Range.edges(range);
1841
+ var nodeEntries = Node.nodes(r, {
1842
+ reverse: true,
1843
+ pass: (_ref) => {
1844
+ var [, path2] = _ref;
1845
+ return !Range.includes(range, path2);
1846
+ }
1847
+ });
1848
+ for (var [, path] of nodeEntries) {
1849
+ if (!Range.includes(range, path)) {
1850
+ var parent = Node.parent(r, path);
1851
+ var index = path[path.length - 1];
1852
+ parent.children.splice(index, 1);
1853
+ }
1854
+ if (Path.equals(path, end.path)) {
1855
+ var leaf = Node.leaf(r, path);
1856
+ leaf.text = leaf.text.slice(0, end.offset);
1857
+ }
1858
+ if (Path.equals(path, start.path)) {
1859
+ var _leaf = Node.leaf(r, path);
1860
+ _leaf.text = _leaf.text.slice(start.offset);
1861
+ }
1862
+ }
1863
+ if (Editor.isEditor(r)) {
1864
+ r.selection = null;
1865
+ }
1866
+ });
1867
+ return newRoot.children;
1868
+ },
1869
+ get(root, path) {
1870
+ var node = Node.getIf(root, path);
1871
+ if (node === void 0) {
1872
+ throw new Error("Cannot find a descendant at path [".concat(path, "] in node: ").concat(Scrubber.stringify(root)));
1873
+ }
1874
+ return node;
1875
+ },
1876
+ getIf(root, path) {
1877
+ var node = root;
1878
+ for (var i = 0; i < path.length; i++) {
1879
+ var p = path[i];
1880
+ if (Text.isText(node) || !node.children[p]) {
1881
+ return;
1882
+ }
1883
+ node = node.children[p];
1884
+ }
1885
+ return node;
1886
+ },
1887
+ has(root, path) {
1888
+ var node = root;
1889
+ for (var i = 0; i < path.length; i++) {
1890
+ var p = path[i];
1891
+ if (Text.isText(node) || !node.children[p]) {
1892
+ return false;
1893
+ }
1894
+ node = node.children[p];
1895
+ }
1896
+ return true;
1897
+ },
1898
+ isNode(value) {
1899
+ var {
1900
+ deep = false
1901
+ } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1902
+ return Text.isText(value) || Element.isElement(value, {
1903
+ deep
1904
+ }) || Editor.isEditor(value, {
1905
+ deep
1906
+ });
1907
+ },
1908
+ isNodeList(value) {
1909
+ var {
1910
+ deep = false
1911
+ } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1912
+ return Array.isArray(value) && value.every((val) => Node.isNode(val, {
1913
+ deep
1914
+ }));
1915
+ },
1916
+ last(root, path) {
1917
+ var p = path.slice();
1918
+ var n = Node.get(root, p);
1919
+ while (n) {
1920
+ if (Text.isText(n) || n.children.length === 0) {
1921
+ break;
1922
+ } else {
1923
+ var i = n.children.length - 1;
1924
+ n = n.children[i];
1925
+ p.push(i);
1926
+ }
1927
+ }
1928
+ return [n, p];
1929
+ },
1930
+ leaf(root, path) {
1931
+ var node = Node.get(root, path);
1932
+ if (!Text.isText(node)) {
1933
+ throw new Error("Cannot get the leaf node at path [".concat(path, "] because it refers to a non-leaf node: ").concat(Scrubber.stringify(node)));
1934
+ }
1935
+ return node;
1936
+ },
1937
+ levels(root, path) {
1938
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
1939
+ return function* () {
1940
+ for (var p of Path.levels(path, options)) {
1941
+ var n = Node.get(root, p);
1942
+ yield [n, p];
1943
+ }
1944
+ }();
1945
+ },
1946
+ matches(node, props) {
1947
+ return Element.isElement(node) && Element.isElementProps(props) && Element.matches(node, props) || Text.isText(node) && Text.isTextProps(props) && Text.matches(node, props);
1948
+ },
1949
+ nodes(root) {
1950
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
1951
+ return function* () {
1952
+ var {
1953
+ pass,
1954
+ reverse = false
1955
+ } = options;
1956
+ var {
1957
+ from = [],
1958
+ to
1959
+ } = options;
1960
+ var visited = /* @__PURE__ */ new Set();
1961
+ var p = [];
1962
+ var n = root;
1963
+ while (true) {
1964
+ if (to && (reverse ? Path.isBefore(p, to) : Path.isAfter(p, to))) {
1965
+ break;
1966
+ }
1967
+ if (!visited.has(n)) {
1968
+ yield [n, p];
1969
+ }
1970
+ if (!visited.has(n) && !Text.isText(n) && n.children.length !== 0 && (pass == null || pass([n, p]) === false)) {
1971
+ visited.add(n);
1972
+ var nextIndex = reverse ? n.children.length - 1 : 0;
1973
+ if (Path.isAncestor(p, from)) {
1974
+ nextIndex = from[p.length];
1975
+ }
1976
+ p = p.concat(nextIndex);
1977
+ n = Node.get(root, p);
1978
+ continue;
1979
+ }
1980
+ if (p.length === 0) {
1981
+ break;
1982
+ }
1983
+ if (!reverse) {
1984
+ var newPath = Path.next(p);
1985
+ if (Node.has(root, newPath)) {
1986
+ p = newPath;
1987
+ n = Node.get(root, p);
1988
+ continue;
1989
+ }
1990
+ }
1991
+ if (reverse && p[p.length - 1] !== 0) {
1992
+ var _newPath = Path.previous(p);
1993
+ p = _newPath;
1994
+ n = Node.get(root, p);
1995
+ continue;
1996
+ }
1997
+ p = Path.parent(p);
1998
+ n = Node.get(root, p);
1999
+ visited.add(n);
2000
+ }
2001
+ }();
2002
+ },
2003
+ parent(root, path) {
2004
+ var parentPath = Path.parent(path);
2005
+ var p = Node.get(root, parentPath);
2006
+ if (Text.isText(p)) {
2007
+ throw new Error("Cannot get the parent of path [".concat(path, "] because it does not exist in the root."));
2008
+ }
2009
+ return p;
2010
+ },
2011
+ string(node) {
2012
+ if (Text.isText(node)) {
2013
+ return node.text;
2014
+ } else {
2015
+ return node.children.map(Node.string).join("");
2016
+ }
2017
+ },
2018
+ texts(root) {
2019
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2020
+ return function* () {
2021
+ for (var [node, path] of Node.nodes(root, options)) {
2022
+ if (Text.isText(node)) {
2023
+ yield [node, path];
2024
+ }
2025
+ }
2026
+ }();
2027
+ }
2028
+ };
2029
+ function ownKeys$c(e, r) {
2030
+ var t = Object.keys(e);
2031
+ if (Object.getOwnPropertySymbols) {
2032
+ var o = Object.getOwnPropertySymbols(e);
2033
+ r && (o = o.filter(function(r2) {
2034
+ return Object.getOwnPropertyDescriptor(e, r2).enumerable;
2035
+ })), t.push.apply(t, o);
2036
+ }
2037
+ return t;
2038
+ }
2039
+ function _objectSpread$c(e) {
2040
+ for (var r = 1; r < arguments.length; r++) {
2041
+ var t = null != arguments[r] ? arguments[r] : {};
2042
+ r % 2 ? ownKeys$c(Object(t), true).forEach(function(r2) {
2043
+ _defineProperty(e, r2, t[r2]);
2044
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$c(Object(t)).forEach(function(r2) {
2045
+ Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
2046
+ });
2047
+ }
2048
+ return e;
2049
+ }
2050
+ var Operation = {
2051
+ isNodeOperation(value) {
2052
+ return Operation.isOperation(value) && value.type.endsWith("_node");
2053
+ },
2054
+ isOperation(value) {
2055
+ if (!isObject(value)) {
2056
+ return false;
2057
+ }
2058
+ switch (value.type) {
2059
+ case "insert_node":
2060
+ return Path.isPath(value.path) && Node.isNode(value.node);
2061
+ case "insert_text":
2062
+ return typeof value.offset === "number" && typeof value.text === "string" && Path.isPath(value.path);
2063
+ case "merge_node":
2064
+ return typeof value.position === "number" && Path.isPath(value.path) && isObject(value.properties);
2065
+ case "move_node":
2066
+ return Path.isPath(value.path) && Path.isPath(value.newPath);
2067
+ case "remove_node":
2068
+ return Path.isPath(value.path) && Node.isNode(value.node);
2069
+ case "remove_text":
2070
+ return typeof value.offset === "number" && typeof value.text === "string" && Path.isPath(value.path);
2071
+ case "set_node":
2072
+ return Path.isPath(value.path) && isObject(value.properties) && isObject(value.newProperties);
2073
+ case "set_selection":
2074
+ return value.properties === null && Range.isRange(value.newProperties) || value.newProperties === null && Range.isRange(value.properties) || isObject(value.properties) && isObject(value.newProperties);
2075
+ case "split_node":
2076
+ return Path.isPath(value.path) && typeof value.position === "number" && isObject(value.properties);
2077
+ default:
2078
+ return false;
2079
+ }
2080
+ },
2081
+ isOperationList(value) {
2082
+ return Array.isArray(value) && value.every((val) => Operation.isOperation(val));
2083
+ },
2084
+ isSelectionOperation(value) {
2085
+ return Operation.isOperation(value) && value.type.endsWith("_selection");
2086
+ },
2087
+ isTextOperation(value) {
2088
+ return Operation.isOperation(value) && value.type.endsWith("_text");
2089
+ },
2090
+ inverse(op) {
2091
+ switch (op.type) {
2092
+ case "insert_node": {
2093
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2094
+ type: "remove_node"
2095
+ });
2096
+ }
2097
+ case "insert_text": {
2098
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2099
+ type: "remove_text"
2100
+ });
2101
+ }
2102
+ case "merge_node": {
2103
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2104
+ type: "split_node",
2105
+ path: Path.previous(op.path)
2106
+ });
2107
+ }
2108
+ case "move_node": {
2109
+ var {
2110
+ newPath,
2111
+ path
2112
+ } = op;
2113
+ if (Path.equals(newPath, path)) {
2114
+ return op;
2115
+ }
2116
+ if (Path.isSibling(path, newPath)) {
2117
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2118
+ path: newPath,
2119
+ newPath: path
2120
+ });
2121
+ }
2122
+ var inversePath = Path.transform(path, op);
2123
+ var inverseNewPath = Path.transform(Path.next(path), op);
2124
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2125
+ path: inversePath,
2126
+ newPath: inverseNewPath
2127
+ });
2128
+ }
2129
+ case "remove_node": {
2130
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2131
+ type: "insert_node"
2132
+ });
2133
+ }
2134
+ case "remove_text": {
2135
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2136
+ type: "insert_text"
2137
+ });
2138
+ }
2139
+ case "set_node": {
2140
+ var {
2141
+ properties,
2142
+ newProperties
2143
+ } = op;
2144
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2145
+ properties: newProperties,
2146
+ newProperties: properties
2147
+ });
2148
+ }
2149
+ case "set_selection": {
2150
+ var {
2151
+ properties: _properties,
2152
+ newProperties: _newProperties
2153
+ } = op;
2154
+ if (_properties == null) {
2155
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2156
+ properties: _newProperties,
2157
+ newProperties: null
2158
+ });
2159
+ } else if (_newProperties == null) {
2160
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2161
+ properties: null,
2162
+ newProperties: _properties
2163
+ });
2164
+ } else {
2165
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2166
+ properties: _newProperties,
2167
+ newProperties: _properties
2168
+ });
2169
+ }
2170
+ }
2171
+ case "split_node": {
2172
+ return _objectSpread$c(_objectSpread$c({}, op), {}, {
2173
+ type: "merge_node",
2174
+ path: Path.next(op.path)
2175
+ });
2176
+ }
2177
+ }
2178
+ }
2179
+ };
2180
+ var isEditor = function isEditor2(value) {
2181
+ var {
2182
+ deep = false
2183
+ } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2184
+ if (!isObject(value)) {
2185
+ return false;
2186
+ }
2187
+ var isEditor3 = typeof value.addMark === "function" && typeof value.apply === "function" && typeof value.deleteFragment === "function" && typeof value.insertBreak === "function" && typeof value.insertSoftBreak === "function" && typeof value.insertFragment === "function" && typeof value.insertNode === "function" && typeof value.insertText === "function" && typeof value.isElementReadOnly === "function" && typeof value.isInline === "function" && typeof value.isSelectable === "function" && typeof value.isVoid === "function" && typeof value.normalizeNode === "function" && typeof value.onChange === "function" && typeof value.removeMark === "function" && typeof value.getDirtyPaths === "function" && (value.marks === null || isObject(value.marks)) && (value.selection === null || Range.isRange(value.selection)) && (!deep || Node.isNodeList(value.children)) && Operation.isOperationList(value.operations);
2188
+ return isEditor3;
2189
+ };
2190
+ var Editor = {
2191
+ above(editor, options) {
2192
+ return editor.above(options);
2193
+ },
2194
+ addMark(editor, key, value) {
2195
+ editor.addMark(key, value);
2196
+ },
2197
+ after(editor, at, options) {
2198
+ return editor.after(at, options);
2199
+ },
2200
+ before(editor, at, options) {
2201
+ return editor.before(at, options);
2202
+ },
2203
+ deleteBackward(editor) {
2204
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2205
+ var {
2206
+ unit = "character"
2207
+ } = options;
2208
+ editor.deleteBackward(unit);
2209
+ },
2210
+ deleteForward(editor) {
2211
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2212
+ var {
2213
+ unit = "character"
2214
+ } = options;
2215
+ editor.deleteForward(unit);
2216
+ },
2217
+ deleteFragment(editor, options) {
2218
+ editor.deleteFragment(options);
2219
+ },
2220
+ edges(editor, at) {
2221
+ return editor.edges(at);
2222
+ },
2223
+ elementReadOnly(editor) {
2224
+ var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
2225
+ return editor.elementReadOnly(options);
2226
+ },
2227
+ end(editor, at) {
2228
+ return editor.end(at);
2229
+ },
2230
+ first(editor, at) {
2231
+ return editor.first(at);
2232
+ },
2233
+ fragment(editor, at) {
2234
+ return editor.fragment(at);
2235
+ },
2236
+ hasBlocks(editor, element) {
2237
+ return editor.hasBlocks(element);
2238
+ },
2239
+ hasInlines(editor, element) {
2240
+ return editor.hasInlines(element);
2241
+ },
2242
+ hasPath(editor, path) {
2243
+ return editor.hasPath(path);
2244
+ },
2245
+ hasTexts(editor, element) {
2246
+ return editor.hasTexts(element);
2247
+ },
2248
+ insertBreak(editor) {
2249
+ editor.insertBreak();
2250
+ },
2251
+ insertFragment(editor, fragment, options) {
2252
+ editor.insertFragment(fragment, options);
2253
+ },
2254
+ insertNode(editor, node) {
2255
+ editor.insertNode(node);
2256
+ },
2257
+ insertSoftBreak(editor) {
2258
+ editor.insertSoftBreak();
2259
+ },
2260
+ insertText(editor, text) {
2261
+ editor.insertText(text);
2262
+ },
2263
+ isBlock(editor, value) {
2264
+ return editor.isBlock(value);
2265
+ },
2266
+ isEdge(editor, point, at) {
2267
+ return editor.isEdge(point, at);
2268
+ },
2269
+ isEditor(value) {
2270
+ return isEditor(value);
2271
+ },
2272
+ isElementReadOnly(editor, element) {
2273
+ return editor.isElementReadOnly(element);
2274
+ },
2275
+ isEmpty(editor, element) {
2276
+ return editor.isEmpty(element);
2277
+ },
2278
+ isEnd(editor, point, at) {
2279
+ return editor.isEnd(point, at);
2280
+ },
2281
+ isInline(editor, value) {
2282
+ return editor.isInline(value);
2283
+ },
2284
+ isNormalizing(editor) {
2285
+ return editor.isNormalizing();
2286
+ },
2287
+ isSelectable(editor, value) {
2288
+ return editor.isSelectable(value);
2289
+ },
2290
+ isStart(editor, point, at) {
2291
+ return editor.isStart(point, at);
2292
+ },
2293
+ isVoid(editor, value) {
2294
+ return editor.isVoid(value);
2295
+ },
2296
+ last(editor, at) {
2297
+ return editor.last(at);
2298
+ },
2299
+ leaf(editor, at, options) {
2300
+ return editor.leaf(at, options);
2301
+ },
2302
+ levels(editor, options) {
2303
+ return editor.levels(options);
2304
+ },
2305
+ marks(editor) {
2306
+ return editor.getMarks();
2307
+ },
2308
+ next(editor, options) {
2309
+ return editor.next(options);
2310
+ },
2311
+ node(editor, at, options) {
2312
+ return editor.node(at, options);
2313
+ },
2314
+ nodes(editor, options) {
2315
+ return editor.nodes(options);
2316
+ },
2317
+ normalize(editor, options) {
2318
+ editor.normalize(options);
2319
+ },
2320
+ parent(editor, at, options) {
2321
+ return editor.parent(at, options);
2322
+ },
2323
+ path(editor, at, options) {
2324
+ return editor.path(at, options);
2325
+ },
2326
+ pathRef(editor, path, options) {
2327
+ return editor.pathRef(path, options);
2328
+ },
2329
+ pathRefs(editor) {
2330
+ return editor.pathRefs();
2331
+ },
2332
+ point(editor, at, options) {
2333
+ return editor.point(at, options);
2334
+ },
2335
+ pointRef(editor, point, options) {
2336
+ return editor.pointRef(point, options);
2337
+ },
2338
+ pointRefs(editor) {
2339
+ return editor.pointRefs();
2340
+ },
2341
+ positions(editor, options) {
2342
+ return editor.positions(options);
2343
+ },
2344
+ previous(editor, options) {
2345
+ return editor.previous(options);
2346
+ },
2347
+ range(editor, at, to) {
2348
+ return editor.range(at, to);
2349
+ },
2350
+ rangeRef(editor, range, options) {
2351
+ return editor.rangeRef(range, options);
2352
+ },
2353
+ rangeRefs(editor) {
2354
+ return editor.rangeRefs();
2355
+ },
2356
+ removeMark(editor, key) {
2357
+ editor.removeMark(key);
2358
+ },
2359
+ setNormalizing(editor, isNormalizing) {
2360
+ editor.setNormalizing(isNormalizing);
2361
+ },
2362
+ start(editor, at) {
2363
+ return editor.start(at);
2364
+ },
2365
+ string(editor, at, options) {
2366
+ return editor.string(at, options);
2367
+ },
2368
+ unhangRange(editor, range, options) {
2369
+ return editor.unhangRange(range, options);
2370
+ },
2371
+ void(editor, options) {
2372
+ return editor.void(options);
2373
+ },
2374
+ withoutNormalizing(editor, fn) {
2375
+ editor.withoutNormalizing(fn);
2376
+ },
2377
+ shouldMergeNodesRemovePrevNode: (editor, prevNode, curNode) => {
2378
+ return editor.shouldMergeNodesRemovePrevNode(prevNode, curNode);
2379
+ }
2380
+ };
2381
+ function ownKeys$b(e, r) {
2382
+ var t = Object.keys(e);
2383
+ if (Object.getOwnPropertySymbols) {
2384
+ var o = Object.getOwnPropertySymbols(e);
2385
+ r && (o = o.filter(function(r2) {
2386
+ return Object.getOwnPropertyDescriptor(e, r2).enumerable;
2387
+ })), t.push.apply(t, o);
2388
+ }
2389
+ return t;
2390
+ }
2391
+ function _objectSpread$b(e) {
2392
+ for (var r = 1; r < arguments.length; r++) {
2393
+ var t = null != arguments[r] ? arguments[r] : {};
2394
+ r % 2 ? ownKeys$b(Object(t), true).forEach(function(r2) {
2395
+ _defineProperty(e, r2, t[r2]);
2396
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$b(Object(t)).forEach(function(r2) {
2397
+ Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
2398
+ });
2399
+ }
2400
+ return e;
2401
+ }
2402
+ var Point = {
2403
+ compare(point, another) {
2404
+ var result = Path.compare(point.path, another.path);
2405
+ if (result === 0) {
2406
+ if (point.offset < another.offset) return -1;
2407
+ if (point.offset > another.offset) return 1;
2408
+ return 0;
2409
+ }
2410
+ return result;
2411
+ },
2412
+ isAfter(point, another) {
2413
+ return Point.compare(point, another) === 1;
2414
+ },
2415
+ isBefore(point, another) {
2416
+ return Point.compare(point, another) === -1;
2417
+ },
2418
+ equals(point, another) {
2419
+ return point.offset === another.offset && Path.equals(point.path, another.path);
2420
+ },
2421
+ isPoint(value) {
2422
+ return isObject(value) && typeof value.offset === "number" && Path.isPath(value.path);
2423
+ },
2424
+ transform(point, op) {
2425
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
2426
+ if (point === null) {
2427
+ return null;
2428
+ }
2429
+ var {
2430
+ affinity = "forward"
2431
+ } = options;
2432
+ var {
2433
+ path,
2434
+ offset
2435
+ } = point;
2436
+ switch (op.type) {
2437
+ case "insert_node":
2438
+ case "move_node": {
2439
+ path = Path.transform(path, op, options);
2440
+ break;
2441
+ }
2442
+ case "insert_text": {
2443
+ if (Path.equals(op.path, path) && (op.offset < offset || op.offset === offset && affinity === "forward")) {
2444
+ offset += op.text.length;
2445
+ }
2446
+ break;
2447
+ }
2448
+ case "merge_node": {
2449
+ if (Path.equals(op.path, path)) {
2450
+ offset += op.position;
2451
+ }
2452
+ path = Path.transform(path, op, options);
2453
+ break;
2454
+ }
2455
+ case "remove_text": {
2456
+ if (Path.equals(op.path, path) && op.offset <= offset) {
2457
+ offset -= Math.min(offset - op.offset, op.text.length);
2458
+ }
2459
+ break;
2460
+ }
2461
+ case "remove_node": {
2462
+ if (Path.equals(op.path, path) || Path.isAncestor(op.path, path)) {
2463
+ return null;
2464
+ }
2465
+ path = Path.transform(path, op, options);
2466
+ break;
2467
+ }
2468
+ case "split_node": {
2469
+ if (Path.equals(op.path, path)) {
2470
+ if (op.position === offset && affinity == null) {
2471
+ return null;
2472
+ } else if (op.position < offset || op.position === offset && affinity === "forward") {
2473
+ offset -= op.position;
2474
+ path = Path.transform(path, op, _objectSpread$b(_objectSpread$b({}, options), {}, {
2475
+ affinity: "forward"
2476
+ }));
2477
+ }
2478
+ } else {
2479
+ path = Path.transform(path, op, options);
2480
+ }
2481
+ break;
2482
+ }
2483
+ default:
2484
+ return point;
2485
+ }
2486
+ return {
2487
+ path,
2488
+ offset
2489
+ };
2490
+ }
2491
+ };
2492
+ var _scrubber = void 0;
2493
+ var Scrubber = {
2494
+ setScrubber(scrubber) {
2495
+ _scrubber = scrubber;
2496
+ },
2497
+ stringify(value) {
2498
+ return JSON.stringify(value, _scrubber);
2499
+ }
2500
+ };
2501
+ var _excluded$2 = ["text"];
2502
+ var _excluded2$2 = ["anchor", "focus", "merge"];
2503
+ function ownKeys$a(e, r) {
2504
+ var t = Object.keys(e);
2505
+ if (Object.getOwnPropertySymbols) {
2506
+ var o = Object.getOwnPropertySymbols(e);
2507
+ r && (o = o.filter(function(r2) {
2508
+ return Object.getOwnPropertyDescriptor(e, r2).enumerable;
2509
+ })), t.push.apply(t, o);
2510
+ }
2511
+ return t;
2512
+ }
2513
+ function _objectSpread$a(e) {
2514
+ for (var r = 1; r < arguments.length; r++) {
2515
+ var t = null != arguments[r] ? arguments[r] : {};
2516
+ r % 2 ? ownKeys$a(Object(t), true).forEach(function(r2) {
2517
+ _defineProperty(e, r2, t[r2]);
2518
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$a(Object(t)).forEach(function(r2) {
2519
+ Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
2520
+ });
2521
+ }
2522
+ return e;
2523
+ }
2524
+ var Text = {
2525
+ equals(text, another) {
2526
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
2527
+ var {
2528
+ loose = false
2529
+ } = options;
2530
+ function omitText(obj) {
2531
+ var rest = _objectWithoutProperties(obj, _excluded$2);
2532
+ return rest;
2533
+ }
2534
+ return isDeepEqual(loose ? omitText(text) : text, loose ? omitText(another) : another);
2535
+ },
2536
+ isText(value) {
2537
+ return isObject(value) && typeof value.text === "string";
2538
+ },
2539
+ isTextList(value) {
2540
+ return Array.isArray(value) && value.every((val) => Text.isText(val));
2541
+ },
2542
+ isTextProps(props) {
2543
+ return props.text !== void 0;
2544
+ },
2545
+ matches(text, props) {
2546
+ for (var key in props) {
2547
+ if (key === "text") {
2548
+ continue;
2549
+ }
2550
+ if (!text.hasOwnProperty(key) || text[key] !== props[key]) {
2551
+ return false;
2552
+ }
2553
+ }
2554
+ return true;
2555
+ },
2556
+ decorations(node, decorations) {
2557
+ var leaves = [{
2558
+ leaf: _objectSpread$a({}, node)
2559
+ }];
2560
+ for (var dec of decorations) {
2561
+ var {
2562
+ anchor,
2563
+ focus,
2564
+ merge: mergeDecoration
2565
+ } = dec, rest = _objectWithoutProperties(dec, _excluded2$2);
2566
+ var [start, end] = Range.edges(dec);
2567
+ var next = [];
2568
+ var leafEnd = 0;
2569
+ var decorationStart = start.offset;
2570
+ var decorationEnd = end.offset;
2571
+ var merge = mergeDecoration !== null && mergeDecoration !== void 0 ? mergeDecoration : Object.assign;
2572
+ for (var {
2573
+ leaf
2574
+ } of leaves) {
2575
+ var {
2576
+ length
2577
+ } = leaf.text;
2578
+ var leafStart = leafEnd;
2579
+ leafEnd += length;
2580
+ if (decorationStart <= leafStart && leafEnd <= decorationEnd) {
2581
+ merge(leaf, rest);
2582
+ next.push({
2583
+ leaf
2584
+ });
2585
+ continue;
2586
+ }
2587
+ if (decorationStart !== decorationEnd && (decorationStart === leafEnd || decorationEnd === leafStart) || decorationStart > leafEnd || decorationEnd < leafStart || decorationEnd === leafStart && leafStart !== 0) {
2588
+ next.push({
2589
+ leaf
2590
+ });
2591
+ continue;
2592
+ }
2593
+ var middle = leaf;
2594
+ var before = void 0;
2595
+ var after = void 0;
2596
+ if (decorationEnd < leafEnd) {
2597
+ var off = decorationEnd - leafStart;
2598
+ after = {
2599
+ leaf: _objectSpread$a(_objectSpread$a({}, middle), {}, {
2600
+ text: middle.text.slice(off)
2601
+ })
2602
+ };
2603
+ middle = _objectSpread$a(_objectSpread$a({}, middle), {}, {
2604
+ text: middle.text.slice(0, off)
2605
+ });
2606
+ }
2607
+ if (decorationStart > leafStart) {
2608
+ var _off = decorationStart - leafStart;
2609
+ before = {
2610
+ leaf: _objectSpread$a(_objectSpread$a({}, middle), {}, {
2611
+ text: middle.text.slice(0, _off)
2612
+ })
2613
+ };
2614
+ middle = _objectSpread$a(_objectSpread$a({}, middle), {}, {
2615
+ text: middle.text.slice(_off)
2616
+ });
2617
+ }
2618
+ merge(middle, rest);
2619
+ if (before) {
2620
+ next.push(before);
2621
+ }
2622
+ next.push({
2623
+ leaf: middle
2624
+ });
2625
+ if (after) {
2626
+ next.push(after);
2627
+ }
2628
+ }
2629
+ leaves = next;
2630
+ }
2631
+ if (leaves.length > 1) {
2632
+ var currentOffset = 0;
2633
+ for (var [index, item] of leaves.entries()) {
2634
+ var _start = currentOffset;
2635
+ var _end = _start + item.leaf.text.length;
2636
+ var position = {
2637
+ start: _start,
2638
+ end: _end
2639
+ };
2640
+ if (index === 0) position.isFirst = true;
2641
+ if (index === leaves.length - 1) position.isLast = true;
2642
+ item.position = position;
2643
+ currentOffset = _end;
2644
+ }
2645
+ }
2646
+ return leaves;
2647
+ }
2648
+ };
2649
+ var getDefaultInsertLocation = (editor) => {
2650
+ if (editor.selection) {
2651
+ return editor.selection;
2652
+ } else if (editor.children.length > 0) {
2653
+ return Editor.end(editor, []);
2654
+ } else {
2655
+ return [0];
2656
+ }
2657
+ };
2658
+ var CodepointType;
2659
+ (function(CodepointType2) {
2660
+ CodepointType2[CodepointType2["None"] = 0] = "None";
2661
+ CodepointType2[CodepointType2["Extend"] = 1] = "Extend";
2662
+ CodepointType2[CodepointType2["ZWJ"] = 2] = "ZWJ";
2663
+ CodepointType2[CodepointType2["RI"] = 4] = "RI";
2664
+ CodepointType2[CodepointType2["Prepend"] = 8] = "Prepend";
2665
+ CodepointType2[CodepointType2["SpacingMark"] = 16] = "SpacingMark";
2666
+ CodepointType2[CodepointType2["L"] = 32] = "L";
2667
+ CodepointType2[CodepointType2["V"] = 64] = "V";
2668
+ CodepointType2[CodepointType2["T"] = 128] = "T";
2669
+ CodepointType2[CodepointType2["LV"] = 256] = "LV";
2670
+ CodepointType2[CodepointType2["LVT"] = 512] = "LVT";
2671
+ CodepointType2[CodepointType2["ExtPict"] = 1024] = "ExtPict";
2672
+ CodepointType2[CodepointType2["Any"] = 2048] = "Any";
2673
+ })(CodepointType || (CodepointType = {}));
2674
+ var NonBoundaryPairs = [
2675
+ // GB6
2676
+ [CodepointType.L, CodepointType.L | CodepointType.V | CodepointType.LV | CodepointType.LVT],
2677
+ // GB7
2678
+ [CodepointType.LV | CodepointType.V, CodepointType.V | CodepointType.T],
2679
+ // GB8
2680
+ [CodepointType.LVT | CodepointType.T, CodepointType.T],
2681
+ // GB9
2682
+ [CodepointType.Any, CodepointType.Extend | CodepointType.ZWJ],
2683
+ // GB9a
2684
+ [CodepointType.Any, CodepointType.SpacingMark],
2685
+ // GB9b
2686
+ [CodepointType.Prepend, CodepointType.Any],
2687
+ // GB11
2688
+ [CodepointType.ZWJ, CodepointType.ExtPict],
2689
+ // GB12 and GB13
2690
+ [CodepointType.RI, CodepointType.RI]
2691
+ ];
2692
+ var TextTransforms = {
2693
+ delete(editor, options) {
2694
+ editor.delete(options);
2695
+ },
2696
+ insertFragment(editor, fragment, options) {
2697
+ editor.insertFragment(fragment, options);
2698
+ },
2699
+ insertText(editor, text) {
2700
+ var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
2701
+ Editor.withoutNormalizing(editor, () => {
2702
+ var {
2703
+ voids = false
2704
+ } = options;
2705
+ var {
2706
+ at = getDefaultInsertLocation(editor)
2707
+ } = options;
2708
+ if (Path.isPath(at)) {
2709
+ at = Editor.range(editor, at);
2710
+ }
2711
+ if (Range.isRange(at)) {
2712
+ if (Range.isCollapsed(at)) {
2713
+ at = at.anchor;
2714
+ } else {
2715
+ var end = Range.end(at);
2716
+ if (!voids && Editor.void(editor, {
2717
+ at: end
2718
+ })) {
2719
+ return;
2720
+ }
2721
+ var start = Range.start(at);
2722
+ var startRef = Editor.pointRef(editor, start);
2723
+ var endRef = Editor.pointRef(editor, end);
2724
+ Transforms.delete(editor, {
2725
+ at,
2726
+ voids
2727
+ });
2728
+ var startPoint = startRef.unref();
2729
+ var endPoint = endRef.unref();
2730
+ at = startPoint || endPoint;
2731
+ Transforms.setSelection(editor, {
2732
+ anchor: at,
2733
+ focus: at
2734
+ });
2735
+ }
2736
+ }
2737
+ if (!voids && Editor.void(editor, {
2738
+ at
2739
+ }) || Editor.elementReadOnly(editor, {
2740
+ at
2741
+ })) {
2742
+ return;
2743
+ }
2744
+ var {
2745
+ path,
2746
+ offset
2747
+ } = at;
2748
+ if (text.length > 0) editor.apply({
2749
+ type: "insert_text",
2750
+ path,
2751
+ offset,
2752
+ text
2753
+ });
2754
+ });
2755
+ }
2756
+ };
2757
+ function ownKeys$9(e, r) {
2758
+ var t = Object.keys(e);
2759
+ if (Object.getOwnPropertySymbols) {
2760
+ var o = Object.getOwnPropertySymbols(e);
2761
+ r && (o = o.filter(function(r2) {
2762
+ return Object.getOwnPropertyDescriptor(e, r2).enumerable;
2763
+ })), t.push.apply(t, o);
2764
+ }
2765
+ return t;
2766
+ }
2767
+ function _objectSpread$9(e) {
2768
+ for (var r = 1; r < arguments.length; r++) {
2769
+ var t = null != arguments[r] ? arguments[r] : {};
2770
+ r % 2 ? ownKeys$9(Object(t), true).forEach(function(r2) {
2771
+ _defineProperty(e, r2, t[r2]);
2772
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$9(Object(t)).forEach(function(r2) {
2773
+ Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
2774
+ });
2775
+ }
2776
+ return e;
2777
+ }
2778
+ var Transforms = _objectSpread$9(_objectSpread$9(_objectSpread$9(_objectSpread$9({}, GeneralTransforms), NodeTransforms), SelectionTransforms), TextTransforms);
2779
+
2780
+ // src/react/ai/utils/findTextRangeInBlock.tsx
2781
+ function maxAllowedDistance(len) {
2782
+ if (len <= 2) return 0;
2783
+ if (len <= 5) return 1;
2784
+ if (len <= 10) return 2;
2785
+ if (len <= 20) return 3;
2786
+ return 5;
2787
+ }
2788
+ function findTextRangeInBlock({
2789
+ block,
2790
+ findText
2791
+ }) {
2792
+ const [blockNode, blockPath] = block;
2793
+ const textSegments = [];
2794
+ let fullText = "";
2795
+ for (const [textNode, textPath] of Node.texts(blockNode)) {
2796
+ const startOffset = fullText.length;
2797
+ const absolutePath = [...blockPath, ...textPath];
2798
+ textSegments.push({
2799
+ offset: startOffset,
2800
+ path: absolutePath,
2801
+ text: textNode.text
2802
+ });
2803
+ fullText += textNode.text;
2804
+ }
2805
+ if (!fullText) return null;
2806
+ let matchStart = fullText.indexOf(findText);
2807
+ let matchEnd = matchStart >= 0 ? matchStart + findText.length : -1;
2808
+ if (matchStart === -1) {
2809
+ const maxDist = maxAllowedDistance(findText.length);
2810
+ let bestMatch = { distance: Infinity, end: -1, start: -1 };
2811
+ for (let i = 0; i <= fullText.length - findText.length; i++) {
2812
+ for (let lenOffset = -maxDist; lenOffset <= maxDist; lenOffset++) {
2813
+ const len = findText.length + lenOffset;
2814
+ if (len <= 0 || i + len > fullText.length) continue;
2815
+ const candidate = fullText.slice(i, i + len);
2816
+ const dist = distance(candidate, findText);
2817
+ if (dist <= maxDist && dist < bestMatch.distance) {
2818
+ bestMatch = { distance: dist, end: i + len, start: i };
2819
+ }
2820
+ }
2821
+ }
2822
+ if (bestMatch.start !== -1) {
2823
+ matchStart = bestMatch.start;
2824
+ matchEnd = bestMatch.end;
2825
+ }
2826
+ }
2827
+ if (matchStart === -1) {
2828
+ for (let prefixLen = findText.length - 1; prefixLen > 0; prefixLen--) {
2829
+ const prefix = findText.slice(0, Math.max(0, prefixLen));
2830
+ const idx = fullText.indexOf(prefix);
2831
+ if (idx !== -1) {
2832
+ matchStart = idx;
2833
+ matchEnd = idx + prefixLen;
2834
+ break;
2835
+ }
2836
+ }
2837
+ }
2838
+ if (matchStart === -1) return null;
2839
+ const findPoint = (charOffset, isEnd = false) => {
2840
+ const accumulated = 0;
2841
+ if (!isEnd) {
2842
+ for (const segment of textSegments) {
2843
+ if (charOffset === segment.offset) {
2844
+ return {
2845
+ offset: 0,
2846
+ path: segment.path
2847
+ };
2848
+ }
2849
+ }
2850
+ }
2851
+ for (const segment of textSegments) {
2852
+ const segmentEnd = segment.offset + segment.text.length;
2853
+ if (charOffset >= segment.offset && charOffset <= segmentEnd) {
2854
+ const localOffset = charOffset - segment.offset;
2855
+ return {
2856
+ offset: localOffset,
2857
+ path: segment.path
2858
+ };
2859
+ }
2860
+ }
2861
+ const lastSegment = textSegments.at(-1);
2862
+ if (!lastSegment) {
2863
+ return { offset: 0, path: blockPath };
2864
+ }
2865
+ return {
2866
+ offset: lastSegment.text.length,
2867
+ path: lastSegment.path
2868
+ };
2869
+ };
2870
+ const anchor = findPoint(matchStart, false);
2871
+ const focus = findPoint(matchEnd, true);
2872
+ return {
2873
+ anchor,
2874
+ focus
2875
+ };
2876
+ }
2877
+
2878
+ // src/react/ai/utils/aiCommentToRange.ts
2879
+ var aiCommentToRange = (editor, aiComment) => {
2880
+ const { blockId, content } = aiComment;
2881
+ const contentNodes = deserializeMd(editor, content);
2882
+ let firstBlock;
2883
+ const ranges = [];
2884
+ contentNodes.forEach((node, index) => {
2885
+ let currentBlock;
2886
+ if (index === 0) {
2887
+ firstBlock = editor.api.node({ id: blockId, at: [] });
2888
+ currentBlock = firstBlock;
2889
+ } else {
2890
+ if (!firstBlock) return;
2891
+ const [_, firstBlockPath] = firstBlock;
2892
+ const blockPath = [firstBlockPath[0] + index];
2893
+ currentBlock = editor.api.node(blockPath);
2894
+ }
2895
+ if (!currentBlock) return;
2896
+ const range = findTextRangeInBlock({
2897
+ block: currentBlock,
2898
+ findText: NodeApi.string(node)
2899
+ });
2900
+ if (!range) return;
2901
+ ranges.push(range);
2902
+ });
2903
+ if (ranges.length === 0) return;
2904
+ if (ranges.length > 1) {
2905
+ const startRange = ranges[0];
2906
+ const endRange = ranges.at(-1);
2907
+ return {
2908
+ anchor: startRange.anchor,
2909
+ focus: endRange.focus
2910
+ };
2911
+ }
2912
+ if (ranges.length === 1) {
2913
+ return ranges[0];
2914
+ }
2915
+ };
2916
+
88
2917
  // src/react/ai-chat/AIChatPlugin.ts
89
- import { BlockSelectionPlugin as BlockSelectionPlugin5 } from "@platejs/selection/react";
2918
+ import { BlockSelectionPlugin as BlockSelectionPlugin4 } from "@platejs/selection/react";
90
2919
  import {
91
2920
  bindFirst as bindFirst2,
92
2921
  ElementApi as ElementApi3,
@@ -96,11 +2925,11 @@ import {
96
2925
  import { createTPlatePlugin } from "platejs/react";
97
2926
 
98
2927
  // src/react/ai-chat/transforms/acceptAIChat.ts
99
- import { KEYS as KEYS3 } from "platejs";
2928
+ import { KEYS as KEYS4 } from "platejs";
100
2929
  import { getEditorPlugin } from "platejs/react";
101
2930
  var acceptAIChat = (editor) => {
102
2931
  const { tf } = getEditorPlugin(editor, AIPlugin);
103
- const api = editor.getApi({ key: KEYS3.ai });
2932
+ const api = editor.getApi({ key: KEYS4.ai });
104
2933
  const lastAINodePath = api.aiChat.node({ at: [], reverse: true })[1];
105
2934
  withAIBatch(editor, () => {
106
2935
  tf.ai.removeMarks();
@@ -118,7 +2947,7 @@ var acceptAIChat = (editor) => {
118
2947
  // src/react/ai-chat/transforms/insertBelowAIChat.ts
119
2948
  import { BlockSelectionPlugin as BlockSelectionPlugin2 } from "@platejs/selection/react";
120
2949
  import cloneDeep2 from "lodash/cloneDeep.js";
121
- import { KEYS as KEYS5, PathApi, RangeApi } from "platejs";
2950
+ import { KEYS as KEYS6, PathApi, RangeApi } from "platejs";
122
2951
 
123
2952
  // src/react/ai-chat/transforms/replaceSelectionAIChat.ts
124
2953
  import {
@@ -127,8 +2956,8 @@ import {
127
2956
  } from "@platejs/selection/react";
128
2957
  import cloneDeep from "lodash/cloneDeep.js";
129
2958
  import {
130
- KEYS as KEYS4,
131
- NodeApi,
2959
+ KEYS as KEYS5,
2960
+ NodeApi as NodeApi2,
132
2961
  TextApi as TextApi2
133
2962
  } from "platejs";
134
2963
  var createFormattedBlocks = ({
@@ -138,10 +2967,10 @@ var createFormattedBlocks = ({
138
2967
  }) => {
139
2968
  if (format === "none") return cloneDeep(blocks);
140
2969
  const [sourceNode] = sourceBlock;
141
- const firstTextEntry = NodeApi.firstText(sourceNode);
2970
+ const firstTextEntry = NodeApi2.firstText(sourceNode);
142
2971
  if (!firstTextEntry) return null;
143
- const blockProps = NodeApi.extractProps(sourceNode);
144
- const textProps = NodeApi.extractProps(firstTextEntry[0]);
2972
+ const blockProps = NodeApi2.extractProps(sourceNode);
2973
+ const textProps = NodeApi2.extractProps(firstTextEntry[0]);
145
2974
  const applyTextFormatting = (node) => {
146
2975
  if (TextApi2.isText(node)) {
147
2976
  return { ...textProps, ...node };
@@ -170,7 +2999,7 @@ var replaceSelectionAIChat = (editor, sourceEditor, { format = "single" } = {})
170
2999
  BlockSelectionPlugin,
171
3000
  "isSelectingSome"
172
3001
  );
173
- editor.getApi({ key: KEYS4.ai }).aiChat.hide();
3002
+ editor.getApi({ key: KEYS5.ai }).aiChat.hide();
174
3003
  if (!isBlockSelecting) {
175
3004
  const firstBlock = editor.api.node({
176
3005
  block: true,
@@ -183,7 +3012,7 @@ var replaceSelectionAIChat = (editor, sourceEditor, { format = "single" } = {})
183
3012
  sourceBlock: firstBlock
184
3013
  });
185
3014
  if (!formattedBlocks2) return;
186
- if (firstBlock[0].type === KEYS4.codeLine && sourceEditor.children[0].type === KEYS4.codeBlock && sourceEditor.children.length === 1) {
3015
+ if (firstBlock[0].type === KEYS5.codeLine && sourceEditor.children[0].type === KEYS5.codeBlock && sourceEditor.children.length === 1) {
187
3016
  editor.tf.insertFragment(formattedBlocks2[0].children);
188
3017
  } else {
189
3018
  editor.tf.insertFragment(formattedBlocks2);
@@ -238,7 +3067,7 @@ var insertBelowAIChat = (editor, sourceEditor, { format = "single" } = {}) => {
238
3067
  BlockSelectionPlugin2,
239
3068
  "isSelectingSome"
240
3069
  );
241
- editor.getApi({ key: KEYS5.ai }).aiChat.hide();
3070
+ editor.getApi({ key: KEYS6.ai }).aiChat.hide();
242
3071
  const insertBlocksAndSelect = editor.getTransforms(BlockSelectionPlugin2).blockSelection.insertBlocksAndSelect;
243
3072
  if (isBlockSelecting) {
244
3073
  const selectedBlocks = editor.getApi(BlockSelectionPlugin2).blockSelection.getNodes();
@@ -293,105 +3122,18 @@ var insertBelowAIChat = (editor, sourceEditor, { format = "single" } = {}) => {
293
3122
  import {
294
3123
  ElementApi,
295
3124
  getPluginType as getPluginType2,
296
- KEYS as KEYS6
3125
+ KEYS as KEYS7
297
3126
  } from "platejs";
298
3127
  var removeAnchorAIChat = (editor, options) => {
299
3128
  editor.tf.withoutSaving(() => {
300
3129
  editor.tf.removeNodes({
301
3130
  at: [],
302
- match: (n) => ElementApi.isElement(n) && n.type === getPluginType2(editor, KEYS6.aiChat),
3131
+ match: (n) => ElementApi.isElement(n) && n.type === getPluginType2(editor, KEYS7.aiChat),
303
3132
  ...options
304
3133
  });
305
3134
  });
306
3135
  };
307
3136
 
308
- // src/react/ai-chat/utils/getEditorPrompt.ts
309
- import { isSelecting } from "@platejs/selection";
310
- import { BlockSelectionPlugin as BlockSelectionPlugin4 } from "@platejs/selection/react";
311
-
312
- // src/react/ai-chat/utils/getMarkdown.ts
313
- import { serializeMd } from "@platejs/markdown";
314
- import { BlockSelectionPlugin as BlockSelectionPlugin3 } from "@platejs/selection/react";
315
- import { KEYS as KEYS7 } from "platejs";
316
- var getMarkdown = (editor, type) => {
317
- if (type === "editor") {
318
- return serializeMd(editor);
319
- }
320
- if (type === "block") {
321
- const blocks = editor.getOption(BlockSelectionPlugin3, "isSelectingSome") ? editor.getApi(BlockSelectionPlugin3).blockSelection.getNodes() : editor.api.nodes({
322
- mode: "highest",
323
- match: (n) => editor.api.isBlock(n)
324
- });
325
- const nodes = Array.from(blocks, (entry) => entry[0]);
326
- return serializeMd(editor, { value: nodes });
327
- }
328
- if (type === "selection") {
329
- const fragment = editor.api.fragment();
330
- if (fragment.length === 1) {
331
- const modifiedFragment = [
332
- {
333
- children: fragment[0].children,
334
- type: KEYS7.p
335
- }
336
- ];
337
- return serializeMd(editor, { value: modifiedFragment });
338
- }
339
- return serializeMd(editor, { value: fragment });
340
- }
341
- return "";
342
- };
343
-
344
- // src/react/ai-chat/utils/getEditorPrompt.ts
345
- var replacePlaceholders = (editor, text, {
346
- prompt
347
- }) => {
348
- let result = text.replace("{prompt}", prompt || "");
349
- const placeholders = {
350
- "{block}": "block",
351
- "{editor}": "editor",
352
- "{selection}": "selection"
353
- };
354
- Object.entries(placeholders).forEach(([placeholder, type]) => {
355
- if (result.includes(placeholder)) {
356
- result = result.replace(placeholder, getMarkdown(editor, type));
357
- }
358
- });
359
- return result;
360
- };
361
- var createPromptFromConfig = (config, params) => {
362
- const { isBlockSelecting, isSelecting: isSelecting3 } = params;
363
- if (isBlockSelecting && config.blockSelecting) {
364
- return config.blockSelecting ?? config.default;
365
- } else if (isSelecting3 && config.selecting) {
366
- return config.selecting ?? config.default;
367
- } else {
368
- return config.default;
369
- }
370
- };
371
- var getEditorPrompt = (editor, {
372
- prompt = "",
373
- promptTemplate = () => "{prompt}"
374
- } = {}) => {
375
- const params = {
376
- editor,
377
- isBlockSelecting: editor.getOption(BlockSelectionPlugin4, "isSelectingSome"),
378
- isSelecting: isSelecting(editor)
379
- };
380
- const template = promptTemplate(params);
381
- if (!template) return;
382
- let promptText = "";
383
- if (typeof prompt === "function") {
384
- promptText = prompt(params);
385
- } else if (typeof prompt === "object") {
386
- promptText = createPromptFromConfig(prompt, params);
387
- } else {
388
- promptText = prompt;
389
- }
390
- return replacePlaceholders(editor, template, {
391
- prompt: promptText
392
- });
393
- };
394
-
395
3137
  // src/react/ai-chat/utils/resetAIChat.ts
396
3138
  import { KEYS as KEYS8 } from "platejs";
397
3139
  import { getEditorPlugin as getEditorPlugin2 } from "platejs/react";
@@ -409,13 +3151,14 @@ var resetAIChat = (editor) => {
409
3151
 
410
3152
  // src/react/ai-chat/utils/submitAIChat.ts
411
3153
  import { isSelecting as isSelecting2 } from "@platejs/selection";
3154
+ import { BlockSelectionPlugin as BlockSelectionPlugin3 } from "@platejs/selection/react";
412
3155
  import { KEYS as KEYS9 } from "platejs";
413
3156
  import { getEditorPlugin as getEditorPlugin3 } from "platejs/react";
414
- var submitAIChat = (editor, {
3157
+ var submitAIChat = (editor, input, {
415
3158
  mode,
416
3159
  options,
417
3160
  prompt,
418
- system
3161
+ toolName
419
3162
  } = {}) => {
420
3163
  const { getOptions, setOption } = getEditorPlugin3(
421
3164
  editor,
@@ -423,12 +3166,12 @@ var submitAIChat = (editor, {
423
3166
  key: KEYS9.aiChat
424
3167
  }
425
3168
  );
426
- const { chat, promptTemplate, systemTemplate } = getOptions();
427
- if (!prompt && chat.input?.length === 0) {
3169
+ const { chat } = getOptions();
3170
+ if (!prompt && input?.length === 0) {
428
3171
  return;
429
3172
  }
430
3173
  if (!prompt) {
431
- prompt = chat.input;
3174
+ prompt = input;
432
3175
  }
433
3176
  if (!mode) {
434
3177
  mode = isSelecting2(editor) ? "chat" : "insert";
@@ -437,21 +3180,24 @@ var submitAIChat = (editor, {
437
3180
  editor.getTransforms(AIPlugin).ai.undo();
438
3181
  }
439
3182
  setOption("mode", mode);
440
- chat.setInput?.("");
441
- void chat.append?.(
3183
+ setOption("toolName", toolName ?? null);
3184
+ const blocks = editor.getApi(BlockSelectionPlugin3).blockSelection.getNodes();
3185
+ const promptText = getEditorPrompt(editor, {
3186
+ prompt
3187
+ });
3188
+ const selection = blocks.length > 0 ? editor.api.nodesRange(blocks) : editor.selection;
3189
+ const ctx = {
3190
+ children: editor.children,
3191
+ selection: selection ?? null,
3192
+ toolName: toolName ?? null
3193
+ };
3194
+ void chat.sendMessage?.(
442
3195
  {
443
- content: getEditorPrompt(editor, {
444
- prompt,
445
- promptTemplate
446
- }) ?? "",
447
- role: "user"
3196
+ text: promptText
448
3197
  },
449
3198
  {
450
3199
  body: {
451
- system: getEditorPrompt(editor, {
452
- prompt: system,
453
- promptTemplate: systemTemplate
454
- })
3200
+ ctx
455
3201
  },
456
3202
  ...options
457
3203
  }
@@ -529,14 +3275,12 @@ var AIChatPlugin = createTPlatePlugin({
529
3275
  aiEditor: null,
530
3276
  chat: { messages: [] },
531
3277
  experimental_lastTextId: null,
532
- mode: "chat",
3278
+ mode: "insert",
533
3279
  open: false,
534
3280
  streaming: false,
3281
+ toolName: null,
535
3282
  trigger: " ",
536
- triggerPreviousCharPattern: /^\s?$/,
537
- promptTemplate: () => "{prompt}",
538
- systemTemplate: () => {
539
- }
3283
+ triggerPreviousCharPattern: /^\s?$/
540
3284
  }
541
3285
  }).overrideEditor(withAIChat).extendApi(({ editor, getOption, getOptions, setOption, type }) => {
542
3286
  return {
@@ -573,13 +3317,7 @@ var AIChatPlugin = createTPlatePlugin({
573
3317
  if (mode === "insert") {
574
3318
  editor.getTransforms(AIPlugin).ai.undo();
575
3319
  }
576
- void chat.reload?.({
577
- body: {
578
- system: getEditorPrompt(editor, {
579
- promptTemplate: getOptions().systemTemplate
580
- })
581
- }
582
- });
3320
+ void chat.regenerate?.();
583
3321
  },
584
3322
  stop: () => {
585
3323
  setOption("streaming", false);
@@ -590,7 +3328,7 @@ var AIChatPlugin = createTPlatePlugin({
590
3328
  hide: () => {
591
3329
  api.aiChat.reset();
592
3330
  setOption("open", false);
593
- if (editor.getOption(BlockSelectionPlugin5, "isSelectingSome")) {
3331
+ if (editor.getOption(BlockSelectionPlugin4, "isSelectingSome")) {
594
3332
  } else {
595
3333
  editor.tf.focus();
596
3334
  }
@@ -645,7 +3383,9 @@ function getLastAssistantMessage(editor) {
645
3383
  return messages?.findLast((message) => message.role === "assistant");
646
3384
  }
647
3385
  function useLastAssistantMessage() {
3386
+ const toolName = usePluginOption(AIChatPlugin, "toolName");
648
3387
  const chat = usePluginOption(AIChatPlugin, "chat");
3388
+ if (toolName === "comment") return;
649
3389
  return chat.messages?.findLast((message) => message.role === "assistant");
650
3390
  }
651
3391
 
@@ -654,11 +3394,14 @@ var useChatChunk = ({
654
3394
  onChunk,
655
3395
  onFinish
656
3396
  }) => {
657
- const { isLoading } = usePluginOption2(
3397
+ const { status } = usePluginOption2(
658
3398
  { key: KEYS12.aiChat },
659
3399
  "chat"
660
3400
  );
661
- const content = useLastAssistantMessage()?.content;
3401
+ const isLoading = status === "streaming" || status === "submitted";
3402
+ const content = useLastAssistantMessage()?.parts.find(
3403
+ (part) => part.type === "text"
3404
+ )?.text;
662
3405
  const insertedTextRef = useRef("");
663
3406
  const prevIsLoadingRef = useRef(isLoading);
664
3407
  useEffect2(() => {
@@ -692,7 +3435,7 @@ var useChatChunk = ({
692
3435
 
693
3436
  // src/react/ai-chat/hooks/useEditorChat.ts
694
3437
  import { useEffect as useEffect3 } from "react";
695
- import { BlockSelectionPlugin as BlockSelectionPlugin6 } from "@platejs/selection/react";
3438
+ import { BlockSelectionPlugin as BlockSelectionPlugin5 } from "@platejs/selection/react";
696
3439
  import { useEditorPlugin as useEditorPlugin2, usePluginOption as usePluginOption3 } from "platejs/react";
697
3440
  var useEditorChat = ({
698
3441
  chat,
@@ -701,18 +3444,15 @@ var useEditorChat = ({
701
3444
  onOpenCursor,
702
3445
  onOpenSelection
703
3446
  }) => {
704
- const { editor, setOption } = useEditorPlugin2(AIChatPlugin);
3447
+ const { editor } = useEditorPlugin2(AIChatPlugin);
705
3448
  const open = usePluginOption3(AIChatPlugin, "open");
706
- useEffect3(() => {
707
- setOption("chat", chat);
708
- }, [chat.input, chat.messages, chat.isLoading, chat.data, chat.error]);
709
3449
  useEffect3(() => {
710
3450
  onOpenChange?.(open);
711
3451
  if (open) {
712
3452
  if (onOpenBlockSelection) {
713
- const blockSelectionApi = editor.getApi(BlockSelectionPlugin6).blockSelection;
3453
+ const blockSelectionApi = editor.getApi(BlockSelectionPlugin5).blockSelection;
714
3454
  const isBlockSelecting = editor.getOption(
715
- BlockSelectionPlugin6,
3455
+ BlockSelectionPlugin5,
716
3456
  "isSelectingSome"
717
3457
  );
718
3458
  if (isBlockSelecting) {
@@ -732,25 +3472,438 @@ var useEditorChat = ({
732
3472
  }, [open]);
733
3473
  };
734
3474
 
3475
+ // src/react/ai-chat/streaming/streamDeserializeInlineMd.ts
3476
+ import { MarkdownPlugin as MarkdownPlugin2 } from "@platejs/markdown";
3477
+ var streamDeserializeInlineMd = (editor, text, options) => {
3478
+ return editor.getApi(MarkdownPlugin2).markdown.deserializeInline(text, options);
3479
+ };
3480
+
3481
+ // src/react/ai-chat/streaming/streamDeserializeMd.ts
3482
+ import { MarkdownPlugin as MarkdownPlugin3 } from "@platejs/markdown";
3483
+ import { getPluginType as getPluginType4, KEYS as KEYS14, TextApi as TextApi3 } from "platejs";
3484
+
3485
+ // src/react/ai-chat/streaming/utils/utils.ts
3486
+ var getChunkTrimmed = (chunk, {
3487
+ direction = "right"
3488
+ } = {}) => {
3489
+ const str = direction === "right" ? chunk.trimEnd() : chunk.trimStart();
3490
+ if (direction === "right") {
3491
+ return chunk.slice(str.length);
3492
+ } else {
3493
+ return chunk.slice(0, chunk.length - str.length);
3494
+ }
3495
+ };
3496
+ function isCompleteCodeBlock(str) {
3497
+ const trimmed = str.trim();
3498
+ const startsWithCodeBlock = trimmed.startsWith("```");
3499
+ const endsWithCodeBlock = trimmed.endsWith("```");
3500
+ return startsWithCodeBlock && endsWithCodeBlock;
3501
+ }
3502
+ function isCompleteMath(str) {
3503
+ const trimmed = str.trim();
3504
+ const startsWithMath = trimmed.startsWith("$$");
3505
+ const endsWithMath = trimmed.endsWith("$$");
3506
+ return startsWithMath && endsWithMath;
3507
+ }
3508
+
3509
+ // src/react/ai-chat/streaming/utils/escapeInput.ts
3510
+ var escapeInput = (data) => {
3511
+ let res = data;
3512
+ if (data.startsWith("$$") && !data.startsWith("$$\n") && !isCompleteMath(data)) {
3513
+ res = data.replace("$$", String.raw`\$\$`);
3514
+ }
3515
+ return res;
3516
+ };
3517
+
3518
+ // src/react/ai-chat/streaming/utils/getListNode.ts
3519
+ var getListNode = (editor, node) => {
3520
+ if (node.listStyleType && node.listStart) {
3521
+ const previousNode = editor.api.previous({
3522
+ at: editor.selection?.focus
3523
+ })?.[0];
3524
+ if (previousNode?.listStyleType && previousNode?.listStart) {
3525
+ return node;
3526
+ } else {
3527
+ if (node.listStart === 1) return node;
3528
+ return {
3529
+ ...node,
3530
+ listRestartPolite: node.listStart
3531
+ };
3532
+ }
3533
+ }
3534
+ return node;
3535
+ };
3536
+
3537
+ // src/react/ai-chat/streaming/utils/isSameNode.ts
3538
+ import { isDefined, KEYS as KEYS13 } from "platejs";
3539
+ var LIST_STYLE_TYPE = "listStyleType";
3540
+ var isSameNode = (editor, node1, node2) => {
3541
+ if (node1.type !== editor.getType(KEYS13.p) || node2.type !== editor.getType(KEYS13.p))
3542
+ return node1.type === node2.type;
3543
+ if (isDefined(node1[LIST_STYLE_TYPE]) || isDefined(node2[LIST_STYLE_TYPE])) {
3544
+ return node1[LIST_STYLE_TYPE] === node2[LIST_STYLE_TYPE];
3545
+ }
3546
+ return node1.type === node2.type;
3547
+ };
3548
+
3549
+ // src/react/ai-chat/streaming/utils/nodesWithProps.ts
3550
+ import { ElementApi as ElementApi4 } from "platejs";
3551
+ var nodesWithProps = (editor, nodes, options) => {
3552
+ return nodes.map((node) => {
3553
+ if (ElementApi4.isElement(node)) {
3554
+ return {
3555
+ ...getListNode(editor, node),
3556
+ ...options.elementProps,
3557
+ children: nodesWithProps(editor, node.children, options)
3558
+ };
3559
+ } else {
3560
+ return {
3561
+ ...options.textProps,
3562
+ ...node,
3563
+ text: node.text
3564
+ };
3565
+ }
3566
+ });
3567
+ };
3568
+
3569
+ // src/react/ai-chat/streaming/streamDeserializeMd.ts
3570
+ var statMdxTagRegex = /<([A-Za-z][A-Za-z0-9._:-]*)(?:\s[^>]*?)?(?<!\/)>/;
3571
+ var streamDeserializeMd = (editor, data, options) => {
3572
+ const input = escapeInput(data);
3573
+ const value = withoutDeserializeInMdx(editor, input);
3574
+ if (Array.isArray(value)) return value;
3575
+ let blocks = [];
3576
+ blocks = editor.getApi(MarkdownPlugin3).markdown.deserialize(input, {
3577
+ ...options,
3578
+ preserveEmptyParagraphs: false
3579
+ });
3580
+ const trimmedData = getChunkTrimmed(data);
3581
+ const lastBlock = blocks.at(-1);
3582
+ const addNewLine = trimmedData === "\n\n";
3583
+ const unshiftNewLine = getChunkTrimmed(data, { direction: "left" }) === "\n\n";
3584
+ const isCodeBlockOrTable = lastBlock?.type === "code_block" || lastBlock?.type === "table";
3585
+ let result = blocks;
3586
+ if (lastBlock && !isCodeBlockOrTable && trimmedData.length > 0 && !addNewLine) {
3587
+ const textNode = [
3588
+ {
3589
+ text: trimmedData
3590
+ }
3591
+ ];
3592
+ const lastChild = lastBlock.children.at(-1);
3593
+ if (lastChild && TextApi3.isText(lastChild) && Object.keys(lastChild).length === 1) {
3594
+ lastBlock.children.pop();
3595
+ const textNode2 = [
3596
+ {
3597
+ text: lastChild.text + trimmedData
3598
+ }
3599
+ ];
3600
+ lastBlock.children.push(...textNode2);
3601
+ } else {
3602
+ lastBlock.children.push(...textNode);
3603
+ }
3604
+ result = [...blocks.slice(0, -1), lastBlock];
3605
+ }
3606
+ if (addNewLine && !isCodeBlockOrTable) {
3607
+ result.push({
3608
+ children: [{ text: "" }],
3609
+ type: KEYS14.p
3610
+ });
3611
+ }
3612
+ if (unshiftNewLine && !isCodeBlockOrTable) {
3613
+ result.unshift({
3614
+ children: [{ text: "" }],
3615
+ type: KEYS14.p
3616
+ });
3617
+ }
3618
+ return result;
3619
+ };
3620
+ var withoutDeserializeInMdx = (editor, input) => {
3621
+ const mdxName = editor.getOption(AIChatPlugin, "_mdxName");
3622
+ if (mdxName) {
3623
+ const isMdxEnd = input.includes(`</${mdxName}>`);
3624
+ if (isMdxEnd) {
3625
+ editor.setOption(AIChatPlugin, "_mdxName", null);
3626
+ return false;
3627
+ } else {
3628
+ return [
3629
+ {
3630
+ children: [
3631
+ {
3632
+ text: input
3633
+ }
3634
+ ],
3635
+ type: getPluginType4(editor, KEYS14.p)
3636
+ }
3637
+ ];
3638
+ }
3639
+ } else {
3640
+ const newMdxName = statMdxTagRegex.exec(input)?.[1];
3641
+ if (input.startsWith(`<${newMdxName}`)) {
3642
+ editor.setOption(AIChatPlugin, "_mdxName", newMdxName ?? null);
3643
+ }
3644
+ }
3645
+ };
3646
+
3647
+ // src/react/ai-chat/streaming/streamInsertChunk.ts
3648
+ import {
3649
+ getPluginType as getPluginType5,
3650
+ KEYS as KEYS16,
3651
+ NodeApi as NodeApi3,
3652
+ PathApi as PathApi2
3653
+ } from "platejs";
3654
+
3655
+ // src/react/ai-chat/streaming/streamSerializeMd.ts
3656
+ import { MarkdownPlugin as MarkdownPlugin4 } from "@platejs/markdown";
3657
+ import {
3658
+ ElementApi as ElementApi5,
3659
+ getPluginKey,
3660
+ KEYS as KEYS15,
3661
+ TextApi as TextApi4
3662
+ } from "platejs";
3663
+ var trimEndHeading = (editor, value) => {
3664
+ const headingKeys = /* @__PURE__ */ new Set([
3665
+ KEYS15.h1,
3666
+ KEYS15.h2,
3667
+ KEYS15.h3,
3668
+ KEYS15.h4,
3669
+ KEYS15.h5,
3670
+ KEYS15.h6
3671
+ ]);
3672
+ const lastBlock = value.at(-1);
3673
+ if (lastBlock && headingKeys.has(
3674
+ getPluginKey(editor, lastBlock.type) ?? lastBlock.type
3675
+ ) && ElementApi5.isElement(lastBlock)) {
3676
+ const lastTextNode = lastBlock.children.at(-1);
3677
+ if (TextApi4.isText(lastTextNode)) {
3678
+ const trimmedText = getChunkTrimmed(lastTextNode?.text);
3679
+ const newChildren = [
3680
+ ...lastBlock.children.slice(0, -1),
3681
+ { text: lastTextNode.text.trimEnd() }
3682
+ ];
3683
+ const newLastBlock = {
3684
+ ...lastBlock,
3685
+ children: newChildren
3686
+ };
3687
+ return {
3688
+ trimmedText,
3689
+ value: [...value.slice(0, -1), newLastBlock]
3690
+ };
3691
+ }
3692
+ }
3693
+ return { trimmedText: "", value };
3694
+ };
3695
+ var streamSerializeMd = (editor, options, chunk) => {
3696
+ const { value: optionsValue, ...restOptions } = options;
3697
+ const { value } = trimEndHeading(editor, optionsValue ?? editor.children);
3698
+ let result = "";
3699
+ result = editor.getApi(MarkdownPlugin4).markdown.serialize({
3700
+ preserveEmptyParagraphs: false,
3701
+ value,
3702
+ ...restOptions
3703
+ });
3704
+ const trimmedChunk = getChunkTrimmed(chunk);
3705
+ if (isCompleteCodeBlock(result) && !chunk.endsWith("```")) {
3706
+ result = result.trimEnd().slice(0, -3) + trimmedChunk;
3707
+ }
3708
+ if (isCompleteMath(result) && !chunk.endsWith("$$")) {
3709
+ result = result.trimEnd().slice(0, -3) + trimmedChunk;
3710
+ }
3711
+ result = result.replace(/&#x20;/g, " ");
3712
+ result = result.replace(/&#x200B;/g, " ");
3713
+ result = result.replace(/\u200B/g, "");
3714
+ if (trimmedChunk !== "\n\n") {
3715
+ result = result.trimEnd() + trimmedChunk;
3716
+ }
3717
+ if (chunk.endsWith("\n\n")) {
3718
+ if (result === "\n") {
3719
+ result = "";
3720
+ } else if (result.endsWith("\n\n")) {
3721
+ result = result.slice(0, -1);
3722
+ }
3723
+ }
3724
+ result = result.replace(/\\([\\`*_{}\\[\]()#+\-\\.!~<>|$])/g, "$1");
3725
+ return result;
3726
+ };
3727
+
3728
+ // src/react/ai-chat/streaming/streamInsertChunk.ts
3729
+ var getNextPath = (path, length) => {
3730
+ let result = path;
3731
+ for (let i = 0; i < length; i++) {
3732
+ result = PathApi2.next(result);
3733
+ }
3734
+ return result;
3735
+ };
3736
+ function streamInsertChunk(editor, chunk, options = {}) {
3737
+ const { _blockChunks, _blockPath } = editor.getOptions(AIChatPlugin);
3738
+ if (_blockPath === null) {
3739
+ const blocks = streamDeserializeMd(editor, chunk);
3740
+ const path = getCurrentBlockPath(editor);
3741
+ const startBlock = editor.api.node(path)[0];
3742
+ const startInEmptyParagraph = NodeApi3.string(startBlock).length === 0 && startBlock.type === getPluginType5(editor, KEYS16.p);
3743
+ if (startInEmptyParagraph) {
3744
+ editor.tf.removeNodes({ at: path });
3745
+ }
3746
+ if (blocks.length > 0) {
3747
+ editor.tf.insertNodes(nodesWithProps(editor, [blocks[0]], options), {
3748
+ at: path,
3749
+ nextBlock: !startInEmptyParagraph,
3750
+ select: true
3751
+ });
3752
+ editor.setOption(AIChatPlugin, "_blockPath", getCurrentBlockPath(editor));
3753
+ editor.setOption(AIChatPlugin, "_blockChunks", chunk);
3754
+ if (blocks.length > 1) {
3755
+ const nextBlocks = blocks.slice(1);
3756
+ const nextPath = getCurrentBlockPath(editor);
3757
+ editor.tf.insertNodes(nodesWithProps(editor, nextBlocks, options), {
3758
+ at: nextPath,
3759
+ nextBlock: true,
3760
+ select: true
3761
+ });
3762
+ const lastBlock = editor.api.node(
3763
+ getNextPath(nextPath, nextBlocks.length)
3764
+ );
3765
+ editor.setOption(AIChatPlugin, "_blockPath", lastBlock[1]);
3766
+ const lastBlockChunks = streamSerializeMd(
3767
+ editor,
3768
+ {
3769
+ value: [lastBlock[0]]
3770
+ },
3771
+ chunk
3772
+ );
3773
+ editor.setOption(AIChatPlugin, "_blockChunks", lastBlockChunks);
3774
+ }
3775
+ }
3776
+ } else {
3777
+ const tempBlockChunks = _blockChunks + chunk;
3778
+ const tempBlocks = streamDeserializeMd(editor, tempBlockChunks);
3779
+ if (tempBlocks.length === 0) {
3780
+ return console.warn(
3781
+ `unsupport md nodes: ${JSON.stringify(tempBlockChunks)}`
3782
+ );
3783
+ }
3784
+ if (tempBlocks.length === 1) {
3785
+ const currentBlock = editor.api.node(_blockPath)[0];
3786
+ if (isSameNode(editor, currentBlock, tempBlocks[0])) {
3787
+ const chunkNodes = streamDeserializeInlineMd(editor, chunk);
3788
+ editor.tf.insertNodes(nodesWithProps(editor, chunkNodes, options), {
3789
+ at: editor.api.end(_blockPath),
3790
+ select: true
3791
+ });
3792
+ const updatedBlock = editor.api.node(_blockPath);
3793
+ const serializedBlock = streamSerializeMd(
3794
+ editor,
3795
+ {
3796
+ value: [updatedBlock[0]]
3797
+ },
3798
+ tempBlockChunks
3799
+ );
3800
+ const blockText = NodeApi3.string(tempBlocks[0]);
3801
+ if (serializedBlock === tempBlockChunks && blockText === serializedBlock) {
3802
+ editor.setOption(AIChatPlugin, "_blockChunks", tempBlockChunks);
3803
+ } else {
3804
+ editor.tf.replaceNodes(
3805
+ nodesWithProps(editor, [tempBlocks[0]], options),
3806
+ {
3807
+ at: _blockPath,
3808
+ select: true
3809
+ }
3810
+ );
3811
+ const serializedBlock2 = streamSerializeMd(
3812
+ editor,
3813
+ {
3814
+ value: [tempBlocks[0]]
3815
+ },
3816
+ tempBlockChunks
3817
+ );
3818
+ editor.setOption(
3819
+ AIChatPlugin,
3820
+ "_blockChunks",
3821
+ // one block includes multiple children
3822
+ tempBlocks[0].type === getPluginType5(editor, KEYS16.codeBlock) || tempBlocks[0].type === getPluginType5(editor, KEYS16.table) || tempBlocks[0].type === getPluginType5(editor, KEYS16.equation) ? tempBlockChunks : serializedBlock2
3823
+ );
3824
+ }
3825
+ } else {
3826
+ const serializedBlock = streamSerializeMd(
3827
+ editor,
3828
+ {
3829
+ value: [tempBlocks[0]]
3830
+ },
3831
+ tempBlockChunks
3832
+ );
3833
+ editor.tf.replaceNodes(
3834
+ nodesWithProps(editor, [tempBlocks[0]], options),
3835
+ {
3836
+ at: _blockPath,
3837
+ select: true
3838
+ }
3839
+ );
3840
+ editor.setOption(AIChatPlugin, "_blockChunks", serializedBlock);
3841
+ }
3842
+ } else {
3843
+ editor.tf.replaceNodes(nodesWithProps(editor, [tempBlocks[0]], options), {
3844
+ at: _blockPath,
3845
+ select: true
3846
+ });
3847
+ if (tempBlocks.length > 1) {
3848
+ const newEndBlockPath = getNextPath(_blockPath, tempBlocks.length - 1);
3849
+ editor.tf.insertNodes(
3850
+ nodesWithProps(editor, tempBlocks.slice(1), options),
3851
+ {
3852
+ at: PathApi2.next(_blockPath),
3853
+ select: true
3854
+ }
3855
+ );
3856
+ editor.setOption(AIChatPlugin, "_blockPath", newEndBlockPath);
3857
+ const endBlock = editor.api.node(newEndBlockPath)[0];
3858
+ const serializedBlock = streamSerializeMd(
3859
+ editor,
3860
+ {
3861
+ value: [endBlock]
3862
+ },
3863
+ tempBlockChunks
3864
+ );
3865
+ editor.setOption(AIChatPlugin, "_blockChunks", serializedBlock);
3866
+ }
3867
+ }
3868
+ }
3869
+ }
3870
+ var getCurrentBlockPath = (editor) => {
3871
+ const getAnchorPreviousPath = (editor2) => {
3872
+ const anchorNode = editor2.getApi(AIChatPlugin).aiChat.node({ anchor: true });
3873
+ if (anchorNode) {
3874
+ return PathApi2.previous(anchorNode[1]);
3875
+ }
3876
+ };
3877
+ const getFocusPath = (editor2) => {
3878
+ return editor2.selection?.focus.path.slice(0, 1);
3879
+ };
3880
+ const path = getAnchorPreviousPath(editor) ?? getFocusPath(editor) ?? [0];
3881
+ const entry = editor.api.node(path);
3882
+ if (entry && (entry[0].type === getPluginType5(editor, KEYS16.columnGroup) || entry[0].type === getPluginType5(editor, KEYS16.table))) {
3883
+ return editor.api.above()?.[1] ?? path;
3884
+ }
3885
+ return path;
3886
+ };
3887
+
735
3888
  // src/react/copilot/CopilotPlugin.tsx
736
- import { serializeMd as serializeMd2 } from "@platejs/markdown";
3889
+ import { serializeMd } from "@platejs/markdown";
737
3890
  import debounce from "lodash/debounce.js";
738
3891
  import {
739
3892
  bindFirst as bindFirst3,
740
- KEYS as KEYS17,
741
- NodeApi as NodeApi2
3893
+ KEYS as KEYS21,
3894
+ NodeApi as NodeApi4
742
3895
  } from "platejs";
743
3896
  import { createTPlatePlugin as createTPlatePlugin2 } from "platejs/react";
744
3897
 
745
3898
  // src/react/copilot/renderCopilotBelowNodes.tsx
746
3899
  import React from "react";
747
- import { KEYS as KEYS13 } from "platejs";
3900
+ import { KEYS as KEYS17 } from "platejs";
748
3901
  import { getEditorPlugin as getEditorPlugin4 } from "platejs/react";
749
3902
  var renderCopilotBelowNodes = ({
750
3903
  editor
751
3904
  }) => {
752
3905
  const copilot = getEditorPlugin4(editor, {
753
- key: KEYS13.copilot
3906
+ key: KEYS17.copilot
754
3907
  });
755
3908
  const { renderGhostText: GhostText } = copilot.getOptions();
756
3909
  if (!GhostText) return;
@@ -761,10 +3914,10 @@ var renderCopilotBelowNodes = ({
761
3914
 
762
3915
  // src/react/copilot/transforms/acceptCopilot.ts
763
3916
  import { deserializeInlineMd } from "@platejs/markdown";
764
- import { KEYS as KEYS14 } from "platejs";
3917
+ import { KEYS as KEYS18 } from "platejs";
765
3918
  var acceptCopilot = (editor) => {
766
3919
  const { suggestionText } = editor.getOptions({
767
- key: KEYS14.copilot
3920
+ key: KEYS18.copilot
768
3921
  });
769
3922
  if (!suggestionText?.length) return false;
770
3923
  editor.tf.insertFragment(deserializeInlineMd(editor, suggestionText));
@@ -772,7 +3925,7 @@ var acceptCopilot = (editor) => {
772
3925
 
773
3926
  // src/react/copilot/transforms/acceptCopilotNextWord.ts
774
3927
  import { deserializeInlineMd as deserializeInlineMd2 } from "@platejs/markdown";
775
- import { KEYS as KEYS16 } from "platejs";
3928
+ import { KEYS as KEYS20 } from "platejs";
776
3929
  import { getEditorPlugin as getEditorPlugin6 } from "platejs/react";
777
3930
 
778
3931
  // src/react/copilot/utils/callCompletionApi.ts
@@ -890,17 +4043,17 @@ var getNextWord = ({ text }) => {
890
4043
  };
891
4044
 
892
4045
  // src/react/copilot/utils/triggerCopilotSuggestion.ts
893
- import { KEYS as KEYS15 } from "platejs";
4046
+ import { KEYS as KEYS19 } from "platejs";
894
4047
  import { getEditorPlugin as getEditorPlugin5 } from "platejs/react";
895
4048
  var triggerCopilotSuggestion = async (editor) => {
896
4049
  const { api, getOptions, setOption } = getEditorPlugin5(
897
4050
  editor,
898
4051
  {
899
- key: KEYS15.copilot
4052
+ key: KEYS19.copilot
900
4053
  }
901
4054
  );
902
4055
  const { completeOptions, getPrompt, isLoading, triggerQuery } = getOptions();
903
- if (isLoading || editor.getOptions({ key: KEYS15.aiChat }).chat?.isLoading) {
4056
+ if (isLoading || editor.getOptions({ key: KEYS19.aiChat }).chat?.isLoading) {
904
4057
  return false;
905
4058
  }
906
4059
  if (!triggerQuery({ editor })) return false;
@@ -934,7 +4087,7 @@ var withoutAbort = (editor, fn) => {
934
4087
  // src/react/copilot/transforms/acceptCopilotNextWord.ts
935
4088
  var acceptCopilotNextWord = (editor) => {
936
4089
  const { api, getOptions } = getEditorPlugin6(editor, {
937
- key: KEYS16.copilot
4090
+ key: KEYS20.copilot
938
4091
  });
939
4092
  const { getNextWord: getNextWord2, suggestionText } = getOptions();
940
4093
  if (!suggestionText?.length) {
@@ -1050,7 +4203,7 @@ var withCopilot = ({
1050
4203
 
1051
4204
  // src/react/copilot/CopilotPlugin.tsx
1052
4205
  var CopilotPlugin = createTPlatePlugin2({
1053
- key: KEYS17.copilot,
4206
+ key: KEYS21.copilot,
1054
4207
  handlers: {
1055
4208
  onBlur: ({ api }) => {
1056
4209
  api.copilot.reject();
@@ -1072,20 +4225,20 @@ var CopilotPlugin = createTPlatePlugin2({
1072
4225
  suggestionNodeId: null,
1073
4226
  suggestionText: null,
1074
4227
  autoTriggerQuery: ({ editor }) => {
1075
- if (editor.getOptions({ key: KEYS17.copilot }).suggestionText) {
4228
+ if (editor.getOptions({ key: KEYS21.copilot }).suggestionText) {
1076
4229
  return false;
1077
4230
  }
1078
4231
  const isEmpty = editor.api.isEmpty(editor.selection, { block: true });
1079
4232
  if (isEmpty) return false;
1080
4233
  const blockAbove = editor.api.block();
1081
4234
  if (!blockAbove) return false;
1082
- const blockString = NodeApi2.string(blockAbove[0]);
4235
+ const blockString = NodeApi4.string(blockAbove[0]);
1083
4236
  return blockString.at(-1) === " ";
1084
4237
  },
1085
4238
  getPrompt: ({ editor }) => {
1086
4239
  const contextEntry = editor.api.block({ highest: true });
1087
4240
  if (!contextEntry) return "";
1088
- return serializeMd2(editor, {
4241
+ return serializeMd(editor, {
1089
4242
  value: [contextEntry[0]]
1090
4243
  });
1091
4244
  },
@@ -1162,17 +4315,29 @@ export {
1162
4315
  acceptAIChat,
1163
4316
  acceptCopilot,
1164
4317
  acceptCopilotNextWord,
4318
+ aiCommentToRange,
1165
4319
  callCompletionApi,
1166
4320
  createFormattedBlocks,
1167
- getEditorPrompt,
4321
+ escapeInput,
4322
+ findTextRangeInBlock,
4323
+ getChunkTrimmed,
4324
+ getCurrentBlockPath,
1168
4325
  getLastAssistantMessage,
1169
- getMarkdown,
4326
+ getListNode,
1170
4327
  getNextWord,
1171
4328
  insertBelowAIChat,
4329
+ isCompleteCodeBlock,
4330
+ isCompleteMath,
4331
+ isSameNode,
4332
+ nodesWithProps,
1172
4333
  removeAnchorAIChat,
1173
4334
  renderCopilotBelowNodes,
1174
4335
  replaceSelectionAIChat,
1175
4336
  resetAIChat,
4337
+ streamDeserializeInlineMd,
4338
+ streamDeserializeMd,
4339
+ streamInsertChunk,
4340
+ streamSerializeMd,
1176
4341
  submitAIChat,
1177
4342
  triggerCopilotSuggestion,
1178
4343
  useAIChatEditor,