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