@jbpark/live-editor 1.11.0 → 1.12.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.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { _ as DEFAULT_TEMPLATE, f as require_lib$1, m as BINDING_PROP, n as createSectionPreviewCache, p as require_lib, v as DRAGGABLE_ITEMS, x as __toESM } from "./document-CBw2uF_P.mjs";
2
- import { a as detectTypeScript, d as replaceSections, i as compile, l as getCachedScriptBlob, n as clearCompilationCache, o as extractSections, r as cn, s as generateSection, t as baseModules, u as preloadScripts } from "./utils-BjYg1Sh8.mjs";
3
- import { _ as parseArrayExpression, c as extract, d as getCurrentValue, f as parseBinding, g as extractObjectProperties, h as extractNodeValue, i as replaceIds, l as nanoid, m as createNodeFromValue, n as clone, o as update, p as arrayExpressionToCode, r as fillIds, t as validateBindingValue, u as findEditableChildren, v as parseValue, y as generateCode } from "./ast-C0FNDLFQ.mjs";
4
- import { generateTailwindCSS } from "./utils/tailwind/index.mjs";
1
+ import { _ as DEFAULT_TEMPLATE, f as require_lib$1, m as BINDING_PROP, n as createSectionPreviewCache, p as require_lib, v as DRAGGABLE_ITEMS, x as __toESM } from "./document-DocoSXLT.mjs";
2
+ import { a as detectTypeScript, d as replaceSections, i as compile, l as getCachedScriptBlob, n as clearCompilationCache, o as extractSections, r as cn, s as generateSection, t as baseModules, u as preloadScripts } from "./utils-DP9WPbBJ.mjs";
3
+ import { _ as parseArrayExpression, c as extract, d as getCurrentValue, f as parseBinding, g as extractObjectProperties, h as extractNodeValue, i as replaceIds, l as nanoid, m as createNodeFromValue, n as clone, o as update, p as arrayExpressionToCode, r as fillIds, t as validateBindingValue, u as findEditableChildren, v as parseValue, y as generateCode } from "./ast-9E8pNi7j.mjs";
4
+ import { t as generateTailwindCSS } from "./tailwind-CzPhj3D9.mjs";
5
5
  import "@jbpark/ui-kit/style.css";
6
6
  import React, { createContext, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
7
7
  import { Button, Card, Checkbox, ColorPicker, DatePicker, Drawer, Input, Select, Space, Toast, Typography, Upload } from "@jbpark/ui-kit";
@@ -24,7 +24,6 @@ import prettierPluginTypeScript from "prettier/plugins/typescript";
24
24
  import Placeholder from "@tiptap/extension-placeholder";
25
25
  import { EditorContent, useEditor } from "@tiptap/react";
26
26
  import StarterKit from "@tiptap/starter-kit";
27
-
28
27
  //#region src/components/context/states.ts
29
28
  const PreviewContext = createContext(void 0);
30
29
  const ErrorContext = createContext(void 0);
@@ -38,7 +37,6 @@ const useError = () => {
38
37
  if (context === void 0) throw new Error("useError must be used within <Live> (ContextProvider)");
39
38
  return context;
40
39
  };
41
-
42
40
  //#endregion
43
41
  //#region src/components/context/context.tsx
44
42
  const ContextProvider = ({ children }) => {
@@ -69,10 +67,8 @@ const ContextProvider = ({ children }) => {
69
67
  })
70
68
  });
71
69
  };
72
-
73
70
  //#endregion
74
71
  //#region src/components/frame/measure.ts
75
- const FALLBACK_PROBE_HEIGHT = 812;
76
72
  const computeProbeHeight = (scrollContainerClientHeight, wrapperInsets) => {
77
73
  const usable = scrollContainerClientHeight - wrapperInsets;
78
74
  return usable > 0 ? usable : null;
@@ -91,7 +87,6 @@ const estimatePositionedElementHeight = (offsetHeight, transform, probeHeight) =
91
87
  const offsetY = parseTranslateY(transform);
92
88
  return Math.min(offsetY + offsetHeight, probeHeight);
93
89
  };
94
-
95
90
  //#endregion
96
91
  //#region src/components/frame/viewport-units.ts
97
92
  const UNIT_MAP = {
@@ -105,7 +100,6 @@ const UNIT_MAP = {
105
100
  const UNITS_PATTERN = Object.keys(UNIT_MAP).sort((a, b) => b.length - a.length).join("|");
106
101
  const VIEWPORT_UNIT_RE = new RegExp(`(?<![\\w.-])(-?(?:\\d+\\.?\\d*|\\.\\d+))(${UNITS_PATTERN})(?![a-zA-Z0-9_-])`, "gi");
107
102
  const convertViewportUnits = (css) => css.replace(VIEWPORT_UNIT_RE, (_match, number, unit) => number + UNIT_MAP[unit.toLowerCase()]);
108
-
109
103
  //#endregion
110
104
  //#region src/components/frame/iframe.tsx
111
105
  const EMPTY_STRING_ARRAY = [];
@@ -278,7 +272,7 @@ const IFrame = ({ title = "Live Preview", sandbox, style = {}, scripts = EMPTY_S
278
272
  if (!doc || !win) return;
279
273
  const scrollParent = iframe.closest("[data-frame-container]");
280
274
  let probeHeight;
281
- if (!scrollParent) probeHeight = FALLBACK_PROBE_HEIGHT;
275
+ if (!scrollParent) probeHeight = 812;
282
276
  else {
283
277
  let wrapperInsets = 0;
284
278
  let node = iframe.parentElement;
@@ -348,7 +342,6 @@ const IFrame = ({ title = "Live Preview", sandbox, style = {}, scripts = EMPTY_S
348
342
  children: content
349
343
  });
350
344
  };
351
-
352
345
  //#endregion
353
346
  //#region src/components/frame/shadow.tsx
354
347
  const Shadow = ({ children }) => {
@@ -359,7 +352,8 @@ const Shadow = ({ children }) => {
359
352
  const [hostContainer, setHostContainer] = useState(null);
360
353
  useLayoutEffect(() => {
361
354
  if (!hostRef.current) return;
362
- setHostContainer(hostRef.current.closest("[data-frame-container]"));
355
+ const container = hostRef.current.closest("[data-frame-container]");
356
+ setHostContainer(container);
363
357
  let shadowRoot = shadowRootRef.current;
364
358
  if (!shadowRoot) {
365
359
  shadowRoot = hostRef.current.shadowRoot || hostRef.current.attachShadow({ mode: "open" });
@@ -382,7 +376,6 @@ const Shadow = ({ children }) => {
382
376
  children: renderTarget && createPortal(children(hostContainer), renderTarget)
383
377
  });
384
378
  };
385
-
386
379
  //#endregion
387
380
  //#region src/components/frame/frame.tsx
388
381
  const Frame = ({ mode, children, ...restProps }) => {
@@ -393,7 +386,6 @@ const Frame = ({ mode, children, ...restProps }) => {
393
386
  children
394
387
  });
395
388
  };
396
-
397
389
  //#endregion
398
390
  //#region src/components/dnd/draggable.tsx
399
391
  const DraggableItem = ({ item, children }) => {
@@ -424,7 +416,6 @@ const DefaultDraggableItem = ({ item, onAdd }) => /* @__PURE__ */ jsx(DraggableI
424
416
  children: item.name
425
417
  })
426
418
  });
427
-
428
419
  //#endregion
429
420
  //#region src/components/dnd/droppable.tsx
430
421
  const Droppable = ({ children, className }) => {
@@ -446,7 +437,6 @@ const Droppable = ({ children, className }) => {
446
437
  })]
447
438
  });
448
439
  };
449
-
450
440
  //#endregion
451
441
  //#region src/components/dnd/renderer.tsx
452
442
  const Renderer = ({ preview, headers, modules, frame, provider }) => {
@@ -483,7 +473,6 @@ const Renderer = ({ preview, headers, modules, frame, provider }) => {
483
473
  });
484
474
  };
485
475
  var renderer_default = memo(Renderer);
486
-
487
476
  //#endregion
488
477
  //#region src/components/dnd/sortable.tsx
489
478
  const Sortable = ({ id, children, selected, onClick, onDelete: _onDelete, onCopy: _onCopy }) => {
@@ -527,7 +516,6 @@ const Sortable = ({ id, children, selected, onClick, onDelete: _onDelete, onCopy
527
516
  ]
528
517
  });
529
518
  };
530
-
531
519
  //#endregion
532
520
  //#region src/components/dnd/overlay.tsx
533
521
  const Overlay = ({ sections, renderProps }) => {
@@ -552,10 +540,10 @@ const Overlay = ({ sections, renderProps }) => {
552
540
  }
553
541
  return null;
554
542
  };
555
-
556
543
  //#endregion
557
544
  //#region node_modules/.pnpm/@marijn+find-cluster-break@1.0.3/node_modules/@marijn/find-cluster-break/src/index.js
558
- let rangeFrom = [], rangeTo = [];
545
+ let rangeFrom = [];
546
+ let rangeTo = [];
559
547
  (() => {
560
548
  let numbers = "lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map((s) => s ? parseInt(s, 36) : 1);
561
549
  for (let i = 0, n = 0; i < numbers.length; i++) (i % 2 ? rangeTo : rangeFrom).push(n = n + numbers[i]);
@@ -623,7 +611,6 @@ function surrogateHigh(ch) {
623
611
  function codePointSize(code) {
624
612
  return code < 65536 ? 1 : 2;
625
613
  }
626
-
627
614
  //#endregion
628
615
  //#region node_modules/.pnpm/@codemirror+state@6.7.1/node_modules/@codemirror/state/dist/index.js
629
616
  /**
@@ -938,7 +925,7 @@ var TextNode = class TextNode extends Text {
938
925
  return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
939
926
  }
940
927
  };
941
- Text.empty = /* @__PURE__ */ new TextLeaf([""], 0);
928
+ Text.empty = /*@__PURE__*/ new TextLeaf([""], 0);
942
929
  function textLength(text) {
943
930
  let length = -1;
944
931
  for (let line of text) length += line.length + 1;
@@ -1072,12 +1059,13 @@ var LineCursor = class {
1072
1059
  } else if (done) {
1073
1060
  this.done = true;
1074
1061
  this.value = "";
1075
- } else if (lineBreak) if (this.afterBreak) this.value = "";
1076
- else {
1077
- this.afterBreak = true;
1078
- this.next();
1079
- }
1080
- else {
1062
+ } else if (lineBreak) {
1063
+ if (this.afterBreak) this.value = "";
1064
+ else {
1065
+ this.afterBreak = true;
1066
+ this.next();
1067
+ }
1068
+ } else {
1081
1069
  this.value = value;
1082
1070
  this.afterBreak = false;
1083
1071
  }
@@ -1135,7 +1123,7 @@ const DefaultSplit = /\r\n?|\n/;
1135
1123
  /**
1136
1124
  Distinguishes different ways in which positions can be mapped.
1137
1125
  */
1138
- var MapMode = /* @__PURE__ */ (function(MapMode) {
1126
+ var MapMode = /*@__PURE__*/ (function(MapMode) {
1139
1127
  /**
1140
1128
  Map a position to a valid new position, even when its context
1141
1129
  was deleted.
@@ -2108,7 +2096,7 @@ function dynamicFacetSlot(addresses, facet, providers) {
2108
2096
  }
2109
2097
  };
2110
2098
  }
2111
- const initField = /* @__PURE__ */ Facet.define({ static: true });
2099
+ const initField = /*@__PURE__*/ Facet.define({ static: true });
2112
2100
  /**
2113
2101
  Fields can store additional information in an editor state, and
2114
2102
  keep it in sync with the rest of the state.
@@ -2210,11 +2198,30 @@ final ordering of extensions is determined by first sorting by
2210
2198
  precedence and then by order within each precedence.
2211
2199
  */
2212
2200
  const Prec = {
2213
- highest: /* @__PURE__ */ prec(Prec_.highest),
2214
- high: /* @__PURE__ */ prec(Prec_.high),
2215
- default: /* @__PURE__ */ prec(Prec_.default),
2216
- low: /* @__PURE__ */ prec(Prec_.low),
2217
- lowest: /* @__PURE__ */ prec(Prec_.lowest)
2201
+ /**
2202
+ The highest precedence level, for extensions that should end up
2203
+ near the start of the precedence ordering.
2204
+ */
2205
+ highest: /*@__PURE__*/ prec(Prec_.highest),
2206
+ /**
2207
+ A higher-than-default precedence, for extensions that should
2208
+ come before those with default precedence.
2209
+ */
2210
+ high: /*@__PURE__*/ prec(Prec_.high),
2211
+ /**
2212
+ The default precedence, which is also used for extensions
2213
+ without an explicit precedence.
2214
+ */
2215
+ default: /*@__PURE__*/ prec(Prec_.default),
2216
+ /**
2217
+ A lower-than-default precedence.
2218
+ */
2219
+ low: /*@__PURE__*/ prec(Prec_.low),
2220
+ /**
2221
+ The lowest precedence level. Meant for things that should end up
2222
+ near the end of the extension order.
2223
+ */
2224
+ lowest: /*@__PURE__*/ prec(Prec_.lowest)
2218
2225
  };
2219
2226
  var PrecExtension = class {
2220
2227
  constructor(inner, prec) {
@@ -2318,7 +2325,8 @@ var Configuration = class Configuration {
2318
2325
  dynamicSlots.push((a) => dynamicFacetSlot(a, facet, providers));
2319
2326
  }
2320
2327
  }
2321
- return new Configuration(base, newCompartments, dynamicSlots.map((f) => f(address)), address, staticValues, facets);
2328
+ let dynamic = dynamicSlots.map((f) => f(address));
2329
+ return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);
2322
2330
  }
2323
2331
  };
2324
2332
  function flatten(extension, compartments, newCompartments) {
@@ -2375,19 +2383,19 @@ function ensureAddr(state, addr) {
2375
2383
  function getAddr(state, addr) {
2376
2384
  return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
2377
2385
  }
2378
- const languageData = /* @__PURE__ */ Facet.define();
2379
- const allowMultipleSelections = /* @__PURE__ */ Facet.define({
2386
+ const languageData = /*@__PURE__*/ Facet.define();
2387
+ const allowMultipleSelections = /*@__PURE__*/ Facet.define({
2380
2388
  combine: (values) => values.some((v) => v),
2381
2389
  static: true
2382
2390
  });
2383
- const lineSeparator = /* @__PURE__ */ Facet.define({
2391
+ const lineSeparator = /*@__PURE__*/ Facet.define({
2384
2392
  combine: (values) => values.length ? values[0] : void 0,
2385
2393
  static: true
2386
2394
  });
2387
- const changeFilter = /* @__PURE__ */ Facet.define();
2388
- const transactionFilter = /* @__PURE__ */ Facet.define();
2389
- const transactionExtender = /* @__PURE__ */ Facet.define();
2390
- const readOnly = /* @__PURE__ */ Facet.define({ combine: (values) => values.length ? values[0] : false });
2395
+ const changeFilter = /*@__PURE__*/ Facet.define();
2396
+ const transactionFilter = /*@__PURE__*/ Facet.define();
2397
+ const transactionExtender = /*@__PURE__*/ Facet.define();
2398
+ const readOnly = /*@__PURE__*/ Facet.define({ combine: (values) => values.length ? values[0] : false });
2391
2399
  /**
2392
2400
  Annotations are tagged values that are used to add metadata to
2393
2401
  transactions in an extensible way. They should be used to model
@@ -2502,11 +2510,11 @@ the editor. Doing this will discard any extensions
2502
2510
  the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)
2503
2511
  compartments.
2504
2512
  */
2505
- StateEffect.reconfigure = /* @__PURE__ */ StateEffect.define();
2513
+ StateEffect.reconfigure = /*@__PURE__*/ StateEffect.define();
2506
2514
  /**
2507
2515
  Append extensions to the top-level configuration of the editor.
2508
2516
  */
2509
- StateEffect.appendConfig = /* @__PURE__ */ StateEffect.define();
2517
+ StateEffect.appendConfig = /*@__PURE__*/ StateEffect.define();
2510
2518
  /**
2511
2519
  Changes to the editor state are grouped into transactions.
2512
2520
  Typically, a user action creates a single transaction, which may
@@ -2608,7 +2616,7 @@ var Transaction = class Transaction {
2608
2616
  Annotation used to store transaction timestamps. Automatically
2609
2617
  added to every transaction, holding `Date.now()`.
2610
2618
  */
2611
- Transaction.time = /* @__PURE__ */ Annotation.define();
2619
+ Transaction.time = /*@__PURE__*/ Annotation.define();
2612
2620
  /**
2613
2621
  Annotation used to associate a transaction with a user interface
2614
2622
  event. Holds a string identifying the event, using a
@@ -2635,19 +2643,19 @@ information. The events used by the core libraries are:
2635
2643
  Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check
2636
2644
  whether the annotation matches a given event.
2637
2645
  */
2638
- Transaction.userEvent = /* @__PURE__ */ Annotation.define();
2646
+ Transaction.userEvent = /*@__PURE__*/ Annotation.define();
2639
2647
  /**
2640
2648
  Annotation indicating whether a transaction should be added to
2641
2649
  the undo history or not.
2642
2650
  */
2643
- Transaction.addToHistory = /* @__PURE__ */ Annotation.define();
2651
+ Transaction.addToHistory = /*@__PURE__*/ Annotation.define();
2644
2652
  /**
2645
2653
  Annotation indicating (when present and true) that a transaction
2646
2654
  represents a change made by some other actor, not the user. This
2647
2655
  is used, for example, to tag other people's changes in
2648
2656
  collaborative editing.
2649
2657
  */
2650
- Transaction.remote = /* @__PURE__ */ Annotation.define();
2658
+ Transaction.remote = /*@__PURE__*/ Annotation.define();
2651
2659
  function joinRanges(a, b) {
2652
2660
  let result = [];
2653
2661
  for (let iA = 0, iB = 0;;) {
@@ -2754,7 +2762,7 @@ The categories produced by a [character
2754
2762
  categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
2755
2763
  do things like selecting by word.
2756
2764
  */
2757
- var CharCategory = /* @__PURE__ */ (function(CharCategory) {
2765
+ var CharCategory = /*@__PURE__*/ (function(CharCategory) {
2758
2766
  /**
2759
2767
  Word characters.
2760
2768
  */
@@ -2772,7 +2780,7 @@ var CharCategory = /* @__PURE__ */ (function(CharCategory) {
2772
2780
  const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
2773
2781
  let wordChar;
2774
2782
  try {
2775
- wordChar = /* @__PURE__ */ new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
2783
+ wordChar = /*@__PURE__*/ new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
2776
2784
  } catch (_) {}
2777
2785
  function hasWordChar(str) {
2778
2786
  if (wordChar) return wordChar.test(str);
@@ -3110,7 +3118,7 @@ Configures the tab size to use in this state. The first
3110
3118
  (highest-precedence) value of the facet is used. If no value is
3111
3119
  given, this defaults to 4.
3112
3120
  */
3113
- EditorState.tabSize = /* @__PURE__ */ Facet.define({ combine: (values) => values.length ? values[0] : 4 });
3121
+ EditorState.tabSize = /*@__PURE__*/ Facet.define({ combine: (values) => values.length ? values[0] : 4 });
3114
3122
  /**
3115
3123
  The line separator to use. By default, any of `"\n"`, `"\r\n"`
3116
3124
  and `"\r"` is treated as a separator when splitting lines, and
@@ -3141,7 +3149,7 @@ Registers translation phrases. The
3141
3149
  all objects registered with this facet to find translations for
3142
3150
  its argument.
3143
3151
  */
3144
- EditorState.phrases = /* @__PURE__ */ Facet.define({ compare(a, b) {
3152
+ EditorState.phrases = /*@__PURE__*/ Facet.define({ compare(a, b) {
3145
3153
  let kA = Object.keys(a), kB = Object.keys(b);
3146
3154
  return kA.length == kB.length && kA.every((k) => a[k] == b[k]);
3147
3155
  } });
@@ -3199,7 +3207,7 @@ but do want to process every transaction.
3199
3207
  Extenders run _after_ filters, when both are present.
3200
3208
  */
3201
3209
  EditorState.transactionExtender = transactionExtender;
3202
- Compartment.reconfigure = /* @__PURE__ */ StateEffect.define();
3210
+ Compartment.reconfigure = /*@__PURE__*/ StateEffect.define();
3203
3211
  /**
3204
3212
  Each range is associated with a value, which must inherit from
3205
3213
  this class.
@@ -3453,7 +3461,7 @@ var RangeSet = class RangeSet {
3453
3461
  if they are equivalent in the given range.
3454
3462
  */
3455
3463
  static eq(oldSets, newSets, from = 0, to) {
3456
- if (to == null) to = 999999999;
3464
+ if (to == null) to = 1e9 - 1;
3457
3465
  let a = oldSets.filter((set) => !set.isEmpty && newSets.indexOf(set) < 0);
3458
3466
  let b = newSets.filter((set) => !set.isEmpty && oldSets.indexOf(set) < 0);
3459
3467
  if (a.length != b.length) return false;
@@ -3518,7 +3526,7 @@ var RangeSet = class RangeSet {
3518
3526
  /**
3519
3527
  The empty set of ranges.
3520
3528
  */
3521
- RangeSet.empty = /* @__PURE__ */ new RangeSet([], [], null, -1);
3529
+ RangeSet.empty = /*@__PURE__*/ new RangeSet([], [], null, -1);
3522
3530
  function lazySort(ranges) {
3523
3531
  if (ranges.length > 1) for (let prev = ranges[0], i = 1; i < ranges.length; i++) {
3524
3532
  let cur = ranges[i];
@@ -3672,7 +3680,8 @@ var LayerCursor = class {
3672
3680
  break;
3673
3681
  } else {
3674
3682
  let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
3675
- this.from = chunkPos + chunk.from[this.rangeIndex];
3683
+ let from = chunkPos + chunk.from[this.rangeIndex];
3684
+ this.from = from;
3676
3685
  this.to = chunkPos + chunk.to[this.rangeIndex];
3677
3686
  this.value = chunk.value[this.rangeIndex];
3678
3687
  this.setRangeIndex(this.rangeIndex + 1);
@@ -3912,11 +3921,10 @@ function findColumn(string, col, tabSize, strict) {
3912
3921
  }
3913
3922
  return strict === true ? -1 : string.length;
3914
3923
  }
3915
-
3916
3924
  //#endregion
3917
3925
  //#region node_modules/.pnpm/style-mod@4.1.3/node_modules/style-mod/src/style-mod.js
3918
3926
  const C = "ͼ";
3919
- const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C);
3927
+ const COUNT = typeof Symbol == "undefined" ? "__ͼ" : Symbol.for(C);
3920
3928
  const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet");
3921
3929
  const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {};
3922
3930
  var StyleModule = class {
@@ -4005,7 +4013,6 @@ var StyleSet = class {
4005
4013
  if (this.styleTag && this.styleTag.getAttribute("nonce") != nonce) this.styleTag.setAttribute("nonce", nonce);
4006
4014
  }
4007
4015
  };
4008
-
4009
4016
  //#endregion
4010
4017
  //#region node_modules/.pnpm/w3c-keyname@2.2.8/node_modules/w3c-keyname/index.js
4011
4018
  var base = {
@@ -4088,8 +4095,8 @@ var shift = {
4088
4095
  221: "}",
4089
4096
  222: "\""
4090
4097
  };
4091
- var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
4092
- var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
4098
+ typeof navigator != "undefined" && /Mac/.test(navigator.platform);
4099
+ typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
4093
4100
  for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
4094
4101
  for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i;
4095
4102
  for (var i = 65; i <= 90; i++) {
@@ -4097,40 +4104,39 @@ for (var i = 65; i <= 90; i++) {
4097
4104
  shift[i] = String.fromCharCode(i);
4098
4105
  }
4099
4106
  for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
4100
-
4101
4107
  //#endregion
4102
- //#region node_modules/.pnpm/@codemirror+view@6.39.11/node_modules/@codemirror/view/dist/index.js
4108
+ //#region node_modules/.pnpm/@codemirror+view@6.43.8/node_modules/@codemirror/view/dist/index.js
4103
4109
  let nav = typeof navigator != "undefined" ? navigator : {
4104
4110
  userAgent: "",
4105
4111
  vendor: "",
4106
4112
  platform: ""
4107
4113
  };
4108
4114
  let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } };
4109
- const ie_edge = /* @__PURE__ */ /Edge\/(\d+)/.exec(nav.userAgent);
4110
- const ie_upto10 = /* @__PURE__ */ /MSIE \d/.test(nav.userAgent);
4111
- const ie_11up = /* @__PURE__ */ /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
4115
+ const ie_edge = /*@__PURE__*/ /Edge\/(\d+)/.exec(nav.userAgent);
4116
+ const ie_upto10 = /*@__PURE__*/ /MSIE \d/.test(nav.userAgent);
4117
+ const ie_11up = /*@__PURE__*/ /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
4112
4118
  const ie = !!(ie_upto10 || ie_11up || ie_edge);
4113
- const gecko = !ie && /* @__PURE__ */ /gecko\/(\d+)/i.test(nav.userAgent);
4114
- const chrome = !ie && /* @__PURE__ */ /Chrome\/(\d+)/.exec(nav.userAgent);
4119
+ const gecko = !ie && /*@__PURE__*/ /gecko\/(\d+)/i.test(nav.userAgent);
4120
+ const chrome = !ie && /*@__PURE__*/ /Chrome\/(\d+)/.exec(nav.userAgent);
4115
4121
  const webkit = "webkitFontSmoothing" in doc.documentElement.style;
4116
- const safari = !ie && /* @__PURE__ */ /Apple Computer/.test(nav.vendor);
4117
- const ios = safari && (/* @__PURE__ */ /Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);
4122
+ const safari = !ie && /*@__PURE__*/ /Apple Computer/.test(nav.vendor);
4123
+ const ios = safari && (/*@__PURE__*/ /Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);
4118
4124
  var browser = {
4119
- mac: ios || /* @__PURE__ */ /Mac/.test(nav.platform),
4120
- windows: /* @__PURE__ */ /Win/.test(nav.platform),
4121
- linux: /* @__PURE__ */ /Linux|X11/.test(nav.platform),
4125
+ mac: ios || /*@__PURE__*/ /Mac/.test(nav.platform),
4126
+ windows: /*@__PURE__*/ /Win/.test(nav.platform),
4127
+ linux: /*@__PURE__*/ /Linux|X11/.test(nav.platform),
4122
4128
  ie,
4123
4129
  ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,
4124
4130
  gecko,
4125
- gecko_version: gecko ? +(/* @__PURE__ */ /Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
4131
+ gecko_version: gecko ? +(/*@__PURE__*/ /Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
4126
4132
  chrome: !!chrome,
4127
4133
  chrome_version: chrome ? +chrome[1] : 0,
4128
4134
  ios,
4129
- android: /* @__PURE__ */ /Android\b/.test(nav.userAgent),
4135
+ android: /*@__PURE__*/ /Android\b/.test(nav.userAgent),
4130
4136
  webkit,
4131
- webkit_version: webkit ? +(/* @__PURE__ */ /\bAppleWebKit\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
4137
+ webkit_version: webkit ? +(/*@__PURE__*/ /\bAppleWebKit\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
4132
4138
  safari,
4133
- safari_version: safari ? +(/* @__PURE__ */ /\bVersion\/(\d+(\.\d+)?)/.exec(nav.userAgent) || [0, 0])[1] : 0,
4139
+ safari_version: safari ? +(/*@__PURE__*/ /\bVersion\/(\d+(\.\d+)?)/.exec(nav.userAgent) || [0, 0])[1] : 0,
4134
4140
  tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
4135
4141
  };
4136
4142
  function combineAttrs(source, target) {
@@ -4139,7 +4145,7 @@ function combineAttrs(source, target) {
4139
4145
  else target[name] = source[name];
4140
4146
  return target;
4141
4147
  }
4142
- const noAttrs = /* @__PURE__ */ Object.create(null);
4148
+ const noAttrs = /*@__PURE__*/ Object.create(null);
4143
4149
  function attrsEq(a, b, ignore) {
4144
4150
  if (a == b) return true;
4145
4151
  if (!a) a = noAttrs;
@@ -4213,7 +4219,7 @@ var WidgetType = class {
4213
4219
  couldn't (in which case the widget will be redrawn). The default
4214
4220
  implementation just returns false.
4215
4221
  */
4216
- updateDOM(dom, view) {
4222
+ updateDOM(dom, view, from) {
4217
4223
  return false;
4218
4224
  }
4219
4225
  /**
@@ -4279,7 +4285,7 @@ var WidgetType = class {
4279
4285
  /**
4280
4286
  The different types of blocks that can occur in an editor view.
4281
4287
  */
4282
- var BlockType = /* @__PURE__ */ (function(BlockType) {
4288
+ var BlockType = /*@__PURE__*/ (function(BlockType) {
4283
4289
  /**
4284
4290
  A line of text.
4285
4291
  */
@@ -4458,10 +4464,11 @@ widget that starts inside its range, including blocks starting
4458
4464
  directly at `from` but not including `to`.
4459
4465
  */
4460
4466
  var BlockWrapper = class BlockWrapper extends RangeValue {
4461
- constructor(tagName, attributes) {
4467
+ constructor(tagName, attributes, rank) {
4462
4468
  super();
4463
4469
  this.tagName = tagName;
4464
4470
  this.attributes = attributes;
4471
+ this.rank = rank;
4465
4472
  }
4466
4473
  eq(other) {
4467
4474
  return other == this || other instanceof BlockWrapper && this.tagName == other.tagName && attrsEq(this.attributes, other.attributes);
@@ -4471,7 +4478,7 @@ var BlockWrapper = class BlockWrapper extends RangeValue {
4471
4478
  attributes.
4472
4479
  */
4473
4480
  static create(spec) {
4474
- return new BlockWrapper(spec.tagName, spec.attributes || noAttrs);
4481
+ return new BlockWrapper(spec.tagName, spec.attributes || noAttrs, spec.rank == null ? 50 : Math.max(0, Math.min(spec.rank, 100)));
4475
4482
  }
4476
4483
  /**
4477
4484
  Create a range set from the given block wrapper ranges.
@@ -4534,8 +4541,10 @@ function scanFor(node, off, targetNode, targetOff, dir) {
4534
4541
  function maxOffset(node) {
4535
4542
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
4536
4543
  }
4537
- function flattenRect(rect, left) {
4538
- let x = left ? rect.left : rect.right;
4544
+ function flattenRect(rect, toLeft) {
4545
+ let { left, right } = rect;
4546
+ if (left == right) return rect;
4547
+ let x = toLeft ? left : right;
4539
4548
  return {
4540
4549
  left: x,
4541
4550
  right: x,
@@ -4591,10 +4600,10 @@ function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) {
4591
4600
  }
4592
4601
  let moveX = 0, moveY = 0;
4593
4602
  if (y == "nearest") {
4594
- if (rect.top < bounding.top) {
4603
+ if (rect.top < bounding.top + yMargin) {
4595
4604
  moveY = rect.top - (bounding.top + yMargin);
4596
4605
  if (side > 0 && rect.bottom > bounding.bottom + moveY) moveY = rect.bottom - bounding.bottom + yMargin;
4597
- } else if (rect.bottom > bounding.bottom) {
4606
+ } else if (rect.bottom > bounding.bottom - yMargin) {
4598
4607
  moveY = rect.bottom - bounding.bottom + yMargin;
4599
4608
  if (side < 0 && rect.top - moveY < bounding.top) moveY = rect.top - (bounding.top + yMargin);
4600
4609
  }
@@ -4603,35 +4612,37 @@ function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) {
4603
4612
  moveY = (y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : y == "start" || y == "center" && side < 0 ? rect.top - yMargin : rect.bottom - boundingHeight + yMargin) - bounding.top;
4604
4613
  }
4605
4614
  if (x == "nearest") {
4606
- if (rect.left < bounding.left) {
4615
+ if (rect.left < bounding.left + xMargin) {
4607
4616
  moveX = rect.left - (bounding.left + xMargin);
4608
4617
  if (side > 0 && rect.right > bounding.right + moveX) moveX = rect.right - bounding.right + xMargin;
4609
- } else if (rect.right > bounding.right) {
4618
+ } else if (rect.right > bounding.right - xMargin) {
4610
4619
  moveX = rect.right - bounding.right + xMargin;
4611
4620
  if (side < 0 && rect.left < bounding.left + moveX) moveX = rect.left - (bounding.left + xMargin);
4612
4621
  }
4613
4622
  } else moveX = (x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : x == "start" == ltr ? rect.left - xMargin : rect.right - (bounding.right - bounding.left) + xMargin) - bounding.left;
4614
- if (moveX || moveY) if (top) win.scrollBy(moveX, moveY);
4615
- else {
4616
- let movedX = 0, movedY = 0;
4617
- if (moveY) {
4618
- let start = cur.scrollTop;
4619
- cur.scrollTop += moveY / scaleY;
4620
- movedY = (cur.scrollTop - start) * scaleY;
4621
- }
4622
- if (moveX) {
4623
- let start = cur.scrollLeft;
4624
- cur.scrollLeft += moveX / scaleX;
4625
- movedX = (cur.scrollLeft - start) * scaleX;
4626
- }
4627
- rect = {
4628
- left: rect.left - movedX,
4629
- top: rect.top - movedY,
4630
- right: rect.right - movedX,
4631
- bottom: rect.bottom - movedY
4632
- };
4633
- if (movedX && Math.abs(movedX - moveX) < 1) x = "nearest";
4634
- if (movedY && Math.abs(movedY - moveY) < 1) y = "nearest";
4623
+ if (moveX || moveY) {
4624
+ if (top) win.scrollBy(moveX, moveY);
4625
+ else {
4626
+ let movedX = 0, movedY = 0;
4627
+ if (moveY) {
4628
+ let start = cur.scrollTop;
4629
+ cur.scrollTop += moveY / scaleY;
4630
+ movedY = (cur.scrollTop - start) * scaleY;
4631
+ }
4632
+ if (moveX) {
4633
+ let start = cur.scrollLeft;
4634
+ cur.scrollLeft += moveX / scaleX;
4635
+ movedX = (cur.scrollLeft - start) * scaleX;
4636
+ }
4637
+ rect = {
4638
+ left: rect.left - movedX,
4639
+ top: rect.top - movedY,
4640
+ right: rect.right - movedX,
4641
+ bottom: rect.bottom - movedY
4642
+ };
4643
+ if (movedX && Math.abs(movedX - moveX) < 1) x = "nearest";
4644
+ if (movedY && Math.abs(movedY - moveY) < 1) y = "nearest";
4645
+ }
4635
4646
  }
4636
4647
  if (top) break;
4637
4648
  if (rect.top < bounding.top || rect.bottom > bounding.bottom || rect.left < bounding.left || rect.right > bounding.right) rect = {
@@ -4644,12 +4655,12 @@ function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) {
4644
4655
  } else if (cur.nodeType == 11) cur = cur.host;
4645
4656
  else break;
4646
4657
  }
4647
- function scrollableParents(dom) {
4648
- let doc = dom.ownerDocument, x, y;
4649
- for (let cur = dom.parentNode; cur;) if (cur == doc.body || x && y) break;
4658
+ function scrollableParents(dom, getX = true) {
4659
+ let doc = dom.ownerDocument, x = null, y = null;
4660
+ for (let cur = dom.parentNode; cur;) if (cur == doc.body || (!getX || x) && y) break;
4650
4661
  else if (cur.nodeType == 1) {
4651
4662
  if (!y && cur.scrollHeight > cur.clientHeight) y = cur;
4652
- if (!x && cur.scrollWidth > cur.clientWidth) x = cur;
4663
+ if (getX && !x && cur.scrollWidth > cur.clientWidth) x = cur;
4653
4664
  cur = cur.assignedSlot || cur.parentNode;
4654
4665
  } else if (cur.nodeType == 11) cur = cur.host;
4655
4666
  else break;
@@ -4679,27 +4690,34 @@ var DOMSelectionState = class {
4679
4690
  this.focusOffset = focusOffset;
4680
4691
  }
4681
4692
  };
4693
+ function getScrollStack(target) {
4694
+ let stack = [];
4695
+ for (let cur = target; cur; cur = cur.nodeType == 11 ? cur.host : cur.parentNode) if (cur.nodeType == 1) stack.push({
4696
+ node: cur,
4697
+ left: cur.scrollLeft,
4698
+ top: cur.scrollTop
4699
+ });
4700
+ return stack;
4701
+ }
4702
+ function restoreScrollStack(stack, vert = true) {
4703
+ for (let { node, left, top } of stack) {
4704
+ if (vert && node.scrollTop != top) node.scrollTop = top;
4705
+ if (node.scrollLeft != left) node.scrollLeft = left;
4706
+ }
4707
+ }
4682
4708
  let preventScrollSupported = null;
4683
4709
  if (browser.safari && browser.safari_version >= 26) preventScrollSupported = false;
4684
4710
  function focusPreventScroll(dom) {
4685
4711
  if (dom.setActive) return dom.setActive();
4686
4712
  if (preventScrollSupported) return dom.focus(preventScrollSupported);
4687
- let stack = [];
4688
- for (let cur = dom; cur; cur = cur.parentNode) {
4689
- stack.push(cur, cur.scrollTop, cur.scrollLeft);
4690
- if (cur == cur.ownerDocument) break;
4691
- }
4713
+ let stack = getScrollStack(dom);
4692
4714
  dom.focus(preventScrollSupported == null ? { get preventScroll() {
4693
4715
  preventScrollSupported = { preventScroll: true };
4694
4716
  return true;
4695
4717
  } } : void 0);
4696
4718
  if (!preventScrollSupported) {
4697
4719
  preventScrollSupported = false;
4698
- for (let i = 0; i < stack.length;) {
4699
- let elt = stack[i++], top = stack[i++], left = stack[i++];
4700
- if (elt.scrollTop != top) elt.scrollTop = top;
4701
- if (elt.scrollLeft != left) elt.scrollLeft = left;
4702
- }
4720
+ restoreScrollStack(stack);
4703
4721
  }
4704
4722
  }
4705
4723
  let scratchRange;
@@ -4752,6 +4770,7 @@ function atElementStart(doc, selection) {
4752
4770
  }
4753
4771
  }
4754
4772
  function isScrolledToBottom(elt) {
4773
+ if (elt instanceof Window) return elt.pageYOffset > Math.max(0, elt.document.documentElement.scrollHeight - elt.innerHeight - 4);
4755
4774
  return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);
4756
4775
  }
4757
4776
  function textNodeBefore(startNode, startOffset) {
@@ -4798,7 +4817,7 @@ var DOMPos = class DOMPos {
4798
4817
  /**
4799
4818
  Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
4800
4819
  */
4801
- var Direction = /* @__PURE__ */ (function(Direction) {
4820
+ var Direction = /*@__PURE__*/ (function(Direction) {
4802
4821
  /**
4803
4822
  Left-to-right.
4804
4823
  */
@@ -4809,21 +4828,23 @@ var Direction = /* @__PURE__ */ (function(Direction) {
4809
4828
  Direction[Direction["RTL"] = 1] = "RTL";
4810
4829
  return Direction;
4811
4830
  })(Direction || (Direction = {}));
4812
- const LTR = Direction.LTR, RTL = Direction.RTL;
4831
+ const LTR = Direction.LTR;
4832
+ const RTL = Direction.RTL;
4813
4833
  function dec(str) {
4814
4834
  let result = [];
4815
4835
  for (let i = 0; i < str.length; i++) result.push(1 << +str[i]);
4816
4836
  return result;
4817
4837
  }
4818
- const LowTypes = /* @__PURE__ */ dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
4819
- const ArabicTypes = /* @__PURE__ */ dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
4820
- const Brackets = /* @__PURE__ */ Object.create(null), BracketStack = [];
4838
+ const LowTypes = /*@__PURE__*/ dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
4839
+ const ArabicTypes = /*@__PURE__*/ dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
4840
+ const Brackets = /*@__PURE__*/ Object.create(null);
4841
+ const BracketStack = [];
4821
4842
  for (let p of [
4822
4843
  "()",
4823
4844
  "[]",
4824
4845
  "{}"
4825
4846
  ]) {
4826
- let l = /* @__PURE__ */ p.charCodeAt(0), r = /* @__PURE__ */ p.charCodeAt(1);
4847
+ let l = /*@__PURE__*/ p.charCodeAt(0), r = /*@__PURE__*/ p.charCodeAt(1);
4827
4848
  Brackets[l] = r;
4828
4849
  Brackets[r] = -l;
4829
4850
  }
@@ -4901,9 +4922,10 @@ function computeCharTypes(line, rFrom, rTo, isolates, outerType) {
4901
4922
  }
4902
4923
  for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
4903
4924
  let type = types[i];
4904
- if (type == 128) if (i < to - 1 && prev == types[i + 1] && prev & 24) type = types[i] = prev;
4905
- else types[i] = 256;
4906
- else if (type == 64) {
4925
+ if (type == 128) {
4926
+ if (i < to - 1 && prev == types[i + 1] && prev & 24) type = types[i] = prev;
4927
+ else types[i] = 256;
4928
+ } else if (type == 64) {
4907
4929
  let end = i + 1;
4908
4930
  while (end < to && types[end] == 64) end++;
4909
4931
  let replace = i && prev == 8 || end < rTo && types[end] == 8 ? prevStrong == 1 ? 1 : 8 : 256;
@@ -4919,21 +4941,22 @@ function processBracketPairs(line, rFrom, rTo, isolates, outerType) {
4919
4941
  let oppositeType = outerType == 1 ? 2 : 1;
4920
4942
  for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {
4921
4943
  let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
4922
- for (let i = from, ch, br, type; i < to; i++) if (br = Brackets[ch = line.charCodeAt(i)]) if (br < 0) {
4923
- for (let sJ = sI - 3; sJ >= 0; sJ -= 3) if (BracketStack[sJ + 1] == -br) {
4924
- let flags = BracketStack[sJ + 2];
4925
- let type = flags & 2 ? outerType : !(flags & 4) ? 0 : flags & 1 ? oppositeType : outerType;
4926
- if (type) types[i] = types[BracketStack[sJ]] = type;
4927
- sI = sJ;
4928
- break;
4944
+ for (let i = from, ch, br, type; i < to; i++) if (br = Brackets[ch = line.charCodeAt(i)]) {
4945
+ if (br < 0) {
4946
+ for (let sJ = sI - 3; sJ >= 0; sJ -= 3) if (BracketStack[sJ + 1] == -br) {
4947
+ let flags = BracketStack[sJ + 2];
4948
+ let type = flags & 2 ? outerType : !(flags & 4) ? 0 : flags & 1 ? oppositeType : outerType;
4949
+ if (type) types[i] = types[BracketStack[sJ]] = type;
4950
+ sI = sJ;
4951
+ break;
4952
+ }
4953
+ } else if (BracketStack.length == 189) break;
4954
+ else {
4955
+ BracketStack[sI++] = i;
4956
+ BracketStack[sI++] = ch;
4957
+ BracketStack[sI++] = context;
4929
4958
  }
4930
- } else if (BracketStack.length == 189) break;
4931
- else {
4932
- BracketStack[sI++] = i;
4933
- BracketStack[sI++] = ch;
4934
- BracketStack[sI++] = context;
4935
- }
4936
- else if ((type = types[i]) == 2 || type == 1) {
4959
+ } else if ((type = types[i]) == 2 || type == 1) {
4937
4960
  let embed = type == outerType;
4938
4961
  context = embed ? 0 : 1;
4939
4962
  for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
@@ -5096,20 +5119,20 @@ function autoDirection(text, from, to) {
5096
5119
  }
5097
5120
  return LTR;
5098
5121
  }
5099
- const clickAddsSelectionRange = /* @__PURE__ */ Facet.define();
5100
- const dragMovesSelection$1 = /* @__PURE__ */ Facet.define();
5101
- const mouseSelectionStyle = /* @__PURE__ */ Facet.define();
5102
- const exceptionSink = /* @__PURE__ */ Facet.define();
5103
- const updateListener = /* @__PURE__ */ Facet.define();
5104
- const inputHandler = /* @__PURE__ */ Facet.define();
5105
- const focusChangeEffect = /* @__PURE__ */ Facet.define();
5106
- const clipboardInputFilter = /* @__PURE__ */ Facet.define();
5107
- const clipboardOutputFilter = /* @__PURE__ */ Facet.define();
5108
- const perLineTextDirection = /* @__PURE__ */ Facet.define({ combine: (values) => values.some((x) => x) });
5109
- const nativeSelectionHidden = /* @__PURE__ */ Facet.define({ combine: (values) => values.some((x) => x) });
5110
- const scrollHandler = /* @__PURE__ */ Facet.define();
5122
+ const clickAddsSelectionRange = /*@__PURE__*/ Facet.define();
5123
+ const dragMovesSelection$1 = /*@__PURE__*/ Facet.define();
5124
+ const mouseSelectionStyle = /*@__PURE__*/ Facet.define();
5125
+ const exceptionSink = /*@__PURE__*/ Facet.define();
5126
+ const updateListener = /*@__PURE__*/ Facet.define();
5127
+ const inputHandler = /*@__PURE__*/ Facet.define();
5128
+ const focusChangeEffect = /*@__PURE__*/ Facet.define();
5129
+ const clipboardInputFilter = /*@__PURE__*/ Facet.define();
5130
+ const clipboardOutputFilter = /*@__PURE__*/ Facet.define();
5131
+ const perLineTextDirection = /*@__PURE__*/ Facet.define({ combine: (values) => values.some((x) => x) });
5132
+ const nativeSelectionHidden = /*@__PURE__*/ Facet.define({ combine: (values) => values.some((x) => x) });
5133
+ const scrollHandler = /*@__PURE__*/ Facet.define();
5111
5134
  var ScrollTarget = class ScrollTarget {
5112
- constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5, isSnapshot = false) {
5135
+ constructor(range, y, x, yMargin, xMargin, isSnapshot = false) {
5113
5136
  this.range = range;
5114
5137
  this.y = y;
5115
5138
  this.x = x;
@@ -5124,8 +5147,8 @@ var ScrollTarget = class ScrollTarget {
5124
5147
  return this.range.to <= state.doc.length ? this : new ScrollTarget(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
5125
5148
  }
5126
5149
  };
5127
- const scrollIntoView = /* @__PURE__ */ StateEffect.define({ map: (t, ch) => t.map(ch) });
5128
- const setEditContextFormatting = /* @__PURE__ */ StateEffect.define();
5150
+ const scrollIntoView = /*@__PURE__*/ StateEffect.define({ map: (t, ch) => t.map(ch) });
5151
+ const setEditContextFormatting = /*@__PURE__*/ StateEffect.define();
5129
5152
  /**
5130
5153
  Log or report an unhandled exception in client code. Should
5131
5154
  probably only be used by extension code that allows client code to
@@ -5145,9 +5168,9 @@ function logException(state, exception, context) {
5145
5168
  else if (context) console.error(context + ":", exception);
5146
5169
  else console.error(exception);
5147
5170
  }
5148
- const editable = /* @__PURE__ */ Facet.define({ combine: (values) => values.length ? values[0] : true });
5171
+ const editable = /*@__PURE__*/ Facet.define({ combine: (values) => values.length ? values[0] : true });
5149
5172
  let nextPluginID = 0;
5150
- const viewPlugin = /* @__PURE__ */ Facet.define({ combine(plugins) {
5173
+ const viewPlugin = /*@__PURE__*/ Facet.define({ combine(plugins) {
5151
5174
  return plugins.filter((p, i) => {
5152
5175
  for (let j = 0; j < i; j++) if (plugins[j].plugin == p.plugin) return false;
5153
5176
  return true;
@@ -5250,13 +5273,13 @@ var PluginInstance = class {
5250
5273
  this.spec = this.value = null;
5251
5274
  }
5252
5275
  };
5253
- const editorAttributes = /* @__PURE__ */ Facet.define();
5254
- const contentAttributes = /* @__PURE__ */ Facet.define();
5255
- const decorations = /* @__PURE__ */ Facet.define();
5256
- const blockWrappers = /* @__PURE__ */ Facet.define();
5257
- const outerDecorations = /* @__PURE__ */ Facet.define();
5258
- const atomicRanges = /* @__PURE__ */ Facet.define();
5259
- const bidiIsolatedRanges = /* @__PURE__ */ Facet.define();
5276
+ const editorAttributes = /*@__PURE__*/ Facet.define();
5277
+ const contentAttributes = /*@__PURE__*/ Facet.define();
5278
+ const decorations = /*@__PURE__*/ Facet.define();
5279
+ const blockWrappers = /*@__PURE__*/ Facet.define();
5280
+ const outerDecorations = /*@__PURE__*/ Facet.define();
5281
+ const atomicRanges = /*@__PURE__*/ Facet.define();
5282
+ const bidiIsolatedRanges = /*@__PURE__*/ Facet.define();
5260
5283
  function getIsolatedRanges(view, line) {
5261
5284
  let isolates = view.state.facet(bidiIsolatedRanges);
5262
5285
  if (!isolates.length) return isolates;
@@ -5288,7 +5311,7 @@ function getIsolatedRanges(view, line) {
5288
5311
  });
5289
5312
  return result;
5290
5313
  }
5291
- const scrollMargins = /* @__PURE__ */ Facet.define();
5314
+ const scrollMargins = /*@__PURE__*/ Facet.define();
5292
5315
  function getScrollMargins(view) {
5293
5316
  let left = 0, right = 0, top = 0, bottom = 0;
5294
5317
  for (let source of view.state.facet(scrollMargins)) {
@@ -5307,7 +5330,7 @@ function getScrollMargins(view) {
5307
5330
  bottom
5308
5331
  };
5309
5332
  }
5310
- const styleModule = /* @__PURE__ */ Facet.define();
5333
+ const styleModule = /*@__PURE__*/ Facet.define();
5311
5334
  var ChangedRange = class ChangedRange {
5312
5335
  constructor(fromA, toA, fromB, toB) {
5313
5336
  this.fromA = fromA;
@@ -5512,7 +5535,7 @@ var Tile = class {
5512
5535
  covers(side) {
5513
5536
  return true;
5514
5537
  }
5515
- coordsIn(pos, side) {
5538
+ coordsIn(pos, side, rtl) {
5516
5539
  return null;
5517
5540
  }
5518
5541
  domPosFor(off, side) {
@@ -5693,10 +5716,10 @@ var LineTile = class LineTile extends CompositeTile {
5693
5716
  let child = tile.children[i], end = off + child.length;
5694
5717
  if (end >= pos) {
5695
5718
  if (child.isComposite()) scan(child, pos - off);
5696
- else if ((!after || after.isHidden && (side > 0 || forCoords && onSameLine(after, child))) && (end > pos || child.flags & 32)) {
5719
+ else if ((!after || after.isHidden && (side > 0 && !(after.flags & 32) || forCoords && onSameLine(after, child))) && (end > pos || child.flags & 32 && side <= 1)) {
5697
5720
  after = child;
5698
5721
  afterOff = pos - off;
5699
- } else if (off < pos || child.flags & 16 && !child.isHidden) {
5722
+ } else if (off < pos || child.flags & 16 && !child.isHidden && side >= -1) {
5700
5723
  before = child;
5701
5724
  beforeOff = pos - off;
5702
5725
  }
@@ -5711,10 +5734,10 @@ var LineTile = class LineTile extends CompositeTile {
5711
5734
  offset: target == before ? beforeOff : afterOff
5712
5735
  } : null;
5713
5736
  }
5714
- coordsIn(pos, side) {
5737
+ coordsIn(pos, side, rtl) {
5715
5738
  let found = this.resolveInline(pos, side, true);
5716
5739
  if (!found) return fallbackRect(this);
5717
- return found.tile.coordsIn(Math.max(0, found.offset), side);
5740
+ return found.tile.coordsIn(Math.max(0, found.offset), side, rtl);
5718
5741
  }
5719
5742
  domIn(pos, side) {
5720
5743
  let found = this.resolveInline(pos, side);
@@ -5776,7 +5799,7 @@ var TextTile = class TextTile extends Tile {
5776
5799
  toString() {
5777
5800
  return JSON.stringify(this.text);
5778
5801
  }
5779
- coordsIn(pos, side) {
5802
+ coordsIn(pos, side, rtl) {
5780
5803
  let length = this.dom.nodeValue.length;
5781
5804
  if (pos > length) pos = length;
5782
5805
  let from = pos, to = pos, flatten = 0;
@@ -5796,7 +5819,7 @@ var TextTile = class TextTile extends Tile {
5796
5819
  if (!rects.length) return null;
5797
5820
  let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1];
5798
5821
  if (browser.safari && !flatten && rect.width == 0) rect = Array.prototype.find.call(rects, (r) => r.width) || rect;
5799
- return flatten ? flattenRect(rect, flatten < 0) : rect || null;
5822
+ return rtl == null ? rect : flattenRect(rect, (flatten ? flatten > 0 : side < 0) == rtl);
5800
5823
  }
5801
5824
  static of(text, dom) {
5802
5825
  let tile = new TextTile(dom || document.createTextNode(text), text);
@@ -5869,8 +5892,9 @@ var WidgetBufferTile = class extends Tile {
5869
5892
  get overrideDOMText() {
5870
5893
  return Text.empty;
5871
5894
  }
5872
- coordsIn(pos) {
5873
- return this.dom.getBoundingClientRect();
5895
+ coordsIn(pos, side, rtl) {
5896
+ let rect = this.dom.getBoundingClientRect();
5897
+ return rtl == null ? rect : flattenRect(rect, side > 0 == rtl);
5874
5898
  }
5875
5899
  };
5876
5900
  var TilePointer = class {
@@ -5882,18 +5906,20 @@ var TilePointer = class {
5882
5906
  }
5883
5907
  advance(dist, side, walker) {
5884
5908
  let { tile, index, beforeBreak, parents } = this;
5885
- while (dist || side > 0) if (!tile.isComposite()) if (index == tile.length) {
5886
- beforeBreak = !!tile.breakAfter;
5887
- ({tile, index} = parents.pop());
5888
- index++;
5889
- } else if (!dist) break;
5890
- else {
5891
- let take = Math.min(dist, tile.length - index);
5892
- if (walker) walker.skip(tile, index, index + take);
5893
- dist -= take;
5894
- index += take;
5895
- }
5896
- else if (beforeBreak) {
5909
+ while (dist || side > 0) if (!tile.isComposite()) {
5910
+ let len = tile.length;
5911
+ if (index < len && dist) {
5912
+ let take = Math.min(dist, len - index);
5913
+ if (walker) walker.skip(tile, index, index + take);
5914
+ dist -= take;
5915
+ index += take;
5916
+ }
5917
+ if (index == len) {
5918
+ beforeBreak = !!tile.breakAfter;
5919
+ ({tile, index} = parents.pop());
5920
+ index++;
5921
+ } else if (!dist) break;
5922
+ } else if (beforeBreak) {
5897
5923
  if (!dist) break;
5898
5924
  if (walker) walker.break();
5899
5925
  dist--;
@@ -5954,7 +5980,7 @@ var TileBuilder = class {
5954
5980
  this.flushBuffer();
5955
5981
  let parent = this.ensureMarks(marks, openStart);
5956
5982
  let prev = parent.lastChild;
5957
- if (prev && prev.isText() && !(prev.flags & 8)) {
5983
+ if (prev && prev.isText() && !(prev.flags & 8) && prev.length + text.length < 512) {
5958
5984
  this.cache.reused.set(prev, 2);
5959
5985
  let tile = parent.children[parent.children.length - 1] = new TextTile(prev.dom, prev.text + text);
5960
5986
  tile.parent = parent;
@@ -5990,6 +6016,7 @@ var TileBuilder = class {
5990
6016
  if (oldTile) this.cache.reused.set(oldTile, 2);
5991
6017
  let text = new TextTile(composition.text, composition.text.nodeValue);
5992
6018
  text.flags |= 8;
6019
+ this.pos = composition.range.toB;
5993
6020
  head.append(text);
5994
6021
  }
5995
6022
  addInlineWidget(widget, marks, openStart) {
@@ -6073,7 +6100,8 @@ var TileBuilder = class {
6073
6100
  }
6074
6101
  for (let i = this.wrappers.length - 1; i >= 0; i--) if (this.wrappers[i].to < this.pos) this.wrappers.splice(i, 1);
6075
6102
  for (let cur = this.blockWrappers; cur.value && cur.from <= this.pos; cur.next()) if (cur.to >= this.pos) {
6076
- let wrap = new OpenWrapper(cur.from, cur.to, cur.value, cur.rank), i = this.wrappers.length;
6103
+ let rank = cur.rank * 102 + cur.value.rank;
6104
+ let wrap = new OpenWrapper(cur.from, cur.to, cur.value, rank), i = this.wrappers.length;
6077
6105
  while (i > 0 && (this.wrappers[i - 1].rank - wrap.rank || this.wrappers[i - 1].to - wrap.to) < 0) i--;
6078
6106
  this.wrappers.splice(i, 0, wrap);
6079
6107
  }
@@ -6166,7 +6194,7 @@ var TileCache = class {
6166
6194
  find(cls, test, type = 2) {
6167
6195
  let i = cls.bucket;
6168
6196
  let bucket = this.buckets[i], off = this.index[i];
6169
- for (let j = bucket.length - 1; j >= 0; j--) {
6197
+ for (let j = 0; j < bucket.length; j++) {
6170
6198
  let index = (j + off) % bucket.length, tile = bucket[index];
6171
6199
  if ((!test || test(tile)) && !this.reused.has(tile)) {
6172
6200
  bucket.splice(index, 1);
@@ -6186,7 +6214,7 @@ var TileCache = class {
6186
6214
  i = 0;
6187
6215
  }
6188
6216
  let tile = widgets[i];
6189
- if (!this.reused.has(tile) && (pass == 0 ? tile.widget.compare(widget) : tile.widget.constructor == widget.constructor && widget.updateDOM(tile.dom, this.view))) {
6217
+ if (!this.reused.has(tile) && (pass == 0 ? tile.widget.compare(widget) : tile.widget.constructor == widget.constructor && widget.updateDOM(tile.dom, this.view, tile.widget))) {
6190
6218
  widgets.splice(i, 1);
6191
6219
  if (i < this.index[0]) this.index[0]--;
6192
6220
  if (tile.widget == widget && tile.length == length && (tile.flags & 497) == flags) {
@@ -6249,6 +6277,7 @@ var TileUpdate = class {
6249
6277
  if (composition && next.fromA <= composition.range.fromA && next.toA >= composition.range.toA) {
6250
6278
  this.forward(next.fromA, composition.range.fromA, composition.range.fromA < composition.range.toA ? 1 : -1);
6251
6279
  this.emit(posB, composition.range.fromB);
6280
+ this.builder.flushBuffer();
6252
6281
  this.cache.clear();
6253
6282
  this.builder.addComposition(composition, compositionContext);
6254
6283
  this.text.skip(composition.range.toB - composition.range.fromB);
@@ -6268,21 +6297,22 @@ var TileUpdate = class {
6268
6297
  let activeMarks = getMarks(this.old), openMarks = this.openMarks;
6269
6298
  this.old.advance(length, incEnd ? 1 : -1, {
6270
6299
  skip: (tile, from, to) => {
6271
- if (tile.isWidget()) if (this.openWidget) this.builder.continueWidget(to - from);
6272
- else {
6273
- let widget = to > 0 || from < tile.length ? WidgetTile.of(tile.widget, this.view, to - from, tile.flags & 496, this.cache.maybeReuse(tile)) : this.cache.reuse(tile);
6274
- if (widget.flags & 256) {
6275
- widget.flags &= -2;
6276
- this.builder.addBlockWidget(widget);
6277
- } else {
6278
- this.builder.ensureLine(null);
6279
- this.builder.addInlineWidget(widget, activeMarks, openMarks);
6280
- openMarks = activeMarks.length;
6300
+ if (tile.isWidget()) {
6301
+ if (this.openWidget) this.builder.continueWidget(to - from);
6302
+ else {
6303
+ let widget = to > 0 || from < tile.length ? WidgetTile.of(tile.widget, this.view, to - from, tile.flags & 496, this.cache.maybeReuse(tile)) : this.cache.reuse(tile);
6304
+ if (widget.flags & 256) {
6305
+ widget.flags &= -2;
6306
+ this.builder.addBlockWidget(widget);
6307
+ } else {
6308
+ this.builder.ensureLine(null);
6309
+ this.builder.addInlineWidget(widget, activeMarks, openMarks);
6310
+ openMarks = activeMarks.length;
6311
+ }
6281
6312
  }
6282
- }
6283
- else if (tile.isText()) {
6313
+ } else if (tile.isText()) {
6284
6314
  this.builder.ensureLine(null);
6285
- if (!from && to == tile.length) this.builder.addText(tile.text, activeMarks, openMarks, this.cache.reuse(tile));
6315
+ if (!from && to == tile.length && !this.cache.reused.has(tile)) this.builder.addText(tile.text, activeMarks, openMarks, this.cache.reuse(tile));
6286
6316
  else {
6287
6317
  this.cache.add(tile);
6288
6318
  this.builder.addText(tile.text.slice(from, to), activeMarks, openMarks);
@@ -6326,7 +6356,7 @@ var TileUpdate = class {
6326
6356
  }
6327
6357
  emit(from, to) {
6328
6358
  let pendingLineAttrs = null;
6329
- let b = this.builder, markCount = 0;
6359
+ let b = this.builder, markCount = -1;
6330
6360
  let openEnd = RangeSet.spans(this.decorations, from, to, {
6331
6361
  point: (from, to, deco, active, openStart, index) => {
6332
6362
  if (deco instanceof PointDecoration) {
@@ -6361,15 +6391,16 @@ var TileUpdate = class {
6361
6391
  pos++;
6362
6392
  } else {
6363
6393
  b.ensureLine(pendingLineAttrs);
6364
- b.addText(chars, active, openStart);
6394
+ b.addText(chars, active, pos == from ? openStart : active.length);
6365
6395
  pos += chars.length;
6366
6396
  }
6367
6397
  pendingLineAttrs = null;
6368
6398
  }
6399
+ markCount = active.length;
6369
6400
  }
6370
6401
  });
6371
- b.addLineStartIfNotCovered(pendingLineAttrs);
6372
- this.openWidget = openEnd > markCount;
6402
+ if (markCount > -1) this.openWidget = openEnd > markCount;
6403
+ if (!this.openWidget) b.addLineStartIfNotCovered(pendingLineAttrs);
6373
6404
  this.openMarks = openEnd;
6374
6405
  }
6375
6406
  forward(from, to, side = 1) {
@@ -6387,8 +6418,9 @@ var TileUpdate = class {
6387
6418
  if (parent == this.view.contentDOM) break;
6388
6419
  if (tile instanceof MarkTile) marks.push(tile);
6389
6420
  else if (tile === null || tile === void 0 ? void 0 : tile.isLine()) line = tile;
6421
+ else if (tile instanceof BlockWrapperTile);
6390
6422
  else if (parent.nodeName == "DIV" && !line && parent != this.view.contentDOM) line = new LineTile(parent, lineBaseAttrs);
6391
- else marks.push(MarkTile.of(new MarkDecoration({
6423
+ else if (!line) marks.push(MarkTile.of(new MarkDecoration({
6392
6424
  tagName: parent.nodeName.toLowerCase(),
6393
6425
  attributes: getAttrs(parent)
6394
6426
  }), parent));
@@ -6451,9 +6483,9 @@ var NullWidget = class extends WidgetType {
6451
6483
  return true;
6452
6484
  }
6453
6485
  };
6454
- NullWidget.inline = /* @__PURE__ */ new NullWidget("span");
6455
- NullWidget.block = /* @__PURE__ */ new NullWidget("div");
6456
- const BreakWidget = /* @__PURE__ */ new class extends WidgetType {
6486
+ NullWidget.inline = /*@__PURE__*/ new NullWidget("span");
6487
+ NullWidget.block = /*@__PURE__*/ new NullWidget("div");
6488
+ const BreakWidget = /*@__PURE__*/ new class extends WidgetType {
6457
6489
  toDOM() {
6458
6490
  return document.createElement("br");
6459
6491
  }
@@ -6488,10 +6520,12 @@ var DocView = class {
6488
6520
  update(update) {
6489
6521
  var _a;
6490
6522
  let changedRanges = update.changedRanges;
6491
- if (this.minWidth > 0 && changedRanges.length) if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) this.minWidth = this.minWidthFrom = this.minWidthTo = 0;
6492
- else {
6493
- this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);
6494
- this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);
6523
+ if (this.minWidth > 0 && changedRanges.length) {
6524
+ if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) this.minWidth = this.minWidthFrom = this.minWidthTo = 0;
6525
+ else {
6526
+ this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);
6527
+ this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);
6528
+ }
6495
6529
  }
6496
6530
  this.updateEditContextFormatting(update);
6497
6531
  let readCompositionAt = -1;
@@ -6531,6 +6565,7 @@ var DocView = class {
6531
6565
  if (composition || changes.length) {
6532
6566
  let oldTile = this.tile;
6533
6567
  let builder = new TileUpdate(this.view, oldTile, this.blockWrappers, this.decorations, this.dynamicDecorationMap);
6568
+ if (composition && Tile.get(composition.text)) builder.cache.reused.set(Tile.get(composition.text), 2);
6534
6569
  this.tile = builder.run(changes, composition);
6535
6570
  destroyDropped(oldTile, builder.cache.reused);
6536
6571
  }
@@ -6650,8 +6685,10 @@ var DocView = class {
6650
6685
  for (;;) {
6651
6686
  let parent = node.parentNode;
6652
6687
  if (parent == tile.dom) break;
6653
- if (bias == 0 && parent.firstChild != parent.lastChild) if (node == parent.firstChild) bias = -1;
6654
- else bias = 1;
6688
+ if (bias == 0 && parent.firstChild != parent.lastChild) {
6689
+ if (node == parent.firstChild) bias = -1;
6690
+ else bias = 1;
6691
+ }
6655
6692
  node = parent;
6656
6693
  }
6657
6694
  if (bias < 0) after = node;
@@ -6670,7 +6707,7 @@ var DocView = class {
6670
6707
  }
6671
6708
  domAtPos(pos, side) {
6672
6709
  let { tile, offset } = this.tile.resolveBlock(pos, side);
6673
- if (tile.isWidget()) return tile.domPosFor(pos, side);
6710
+ if (tile.isWidget()) return tile.domPosFor(offset, side);
6674
6711
  return tile.domIn(offset, side);
6675
6712
  }
6676
6713
  inlineDOMNearPos(pos, side) {
@@ -6700,13 +6737,13 @@ var DocView = class {
6700
6737
  else if (afterBad && before) after = null;
6701
6738
  return before && side < 0 || !after ? before.domIn(beforeOff, side) : after.domIn(afterOff, side);
6702
6739
  }
6703
- coordsAt(pos, side) {
6740
+ coordsAt(pos, side, rtl) {
6704
6741
  let { tile, offset } = this.tile.resolveBlock(pos, side);
6705
6742
  if (tile.isWidget()) {
6706
6743
  if (tile.widget instanceof BlockGapWidget) return null;
6707
6744
  return tile.coordsInWidget(offset, side, true);
6708
6745
  }
6709
- return tile.coordsIn(offset, side);
6746
+ return tile.coordsIn(offset, side, rtl);
6710
6747
  }
6711
6748
  lineAt(pos, side) {
6712
6749
  let { tile } = this.tile.resolveBlock(pos, side);
@@ -6874,7 +6911,7 @@ var DocView = class {
6874
6911
  logException(this.view.state, e, "scroll handler");
6875
6912
  }
6876
6913
  let { range } = target;
6877
- let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other;
6914
+ let rect = this.coordsAt(range.head, range.assoc || (range.head > range.anchor ? -1 : 1)), other;
6878
6915
  if (!rect) return;
6879
6916
  if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1))) rect = {
6880
6917
  left: Math.min(rect.left, other.left),
@@ -6891,6 +6928,14 @@ var DocView = class {
6891
6928
  };
6892
6929
  let { offsetWidth, offsetHeight } = this.view.scrollDOM;
6893
6930
  scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == Direction.LTR);
6931
+ if (window.visualViewport && window.innerHeight - window.visualViewport.height > 1 && (rect.top > window.visualViewport.offsetTop + window.visualViewport.height || rect.bottom < window.visualViewport.offsetTop)) {
6932
+ let line = this.view.docView.lineAt(range.head, 1);
6933
+ if (line) {
6934
+ let stack = getScrollStack(line.dom);
6935
+ line.dom.scrollIntoView({ block: "nearest" });
6936
+ restoreScrollStack(stack, false);
6937
+ }
6938
+ }
6894
6939
  }
6895
6940
  lineHasWidget(pos) {
6896
6941
  let scan = (child) => child.isWidget() || child.children.some(scan);
@@ -7044,7 +7089,7 @@ function groupAt(state, pos, bias = 1) {
7044
7089
  if (categorize(line.text.slice(to, next)) != cat) break;
7045
7090
  to = next;
7046
7091
  }
7047
- return EditorSelection.range(from + line.from, to + line.from);
7092
+ return EditorSelection.undirectionalRange(from + line.from, to + line.from);
7048
7093
  }
7049
7094
  function posAtCoordsImprecise(view, contentRect, block, x, y) {
7050
7095
  let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth);
@@ -7117,7 +7162,8 @@ function moveVertically(view, start, forward, distance) {
7117
7162
  if (startPos == (forward ? view.state.doc.length : 0)) return EditorSelection.cursor(startPos, start.assoc);
7118
7163
  let goal = start.goalColumn, startY;
7119
7164
  let rect = view.contentDOM.getBoundingClientRect();
7120
- let startCoords = view.coordsAtPos(startPos, start.assoc || -1), docTop = view.documentTop;
7165
+ let startCoords = view.coordsAtPos(startPos, start.assoc || ((start.empty ? forward : start.head == start.from) ? 1 : -1));
7166
+ let docTop = view.documentTop;
7121
7167
  if (startCoords) {
7122
7168
  if (goal == null) goal = startCoords.left - rect.left;
7123
7169
  startY = dir < 0 ? startCoords.top : startCoords.bottom;
@@ -7127,12 +7173,17 @@ function moveVertically(view, start, forward, distance) {
7127
7173
  startY = (dir < 0 ? line.top : line.bottom) + docTop;
7128
7174
  }
7129
7175
  let resolvedGoal = rect.left + goal;
7130
- let dist = distance !== null && distance !== void 0 ? distance : view.viewState.heightOracle.textHeight >> 1;
7131
- let pos = posAtCoords(view, {
7132
- x: resolvedGoal,
7133
- y: startY + dist * dir
7134
- }, false, dir);
7135
- return EditorSelection.cursor(pos.pos, pos.assoc, void 0, goal);
7176
+ let halfText = view.viewState.heightOracle.textHeight >> 1, dist = distance !== null && distance !== void 0 ? distance : halfText;
7177
+ for (let scan = 0;; scan += halfText) {
7178
+ let y = startY + (dist + scan) * dir;
7179
+ let pos = posAtCoords(view, {
7180
+ x: resolvedGoal,
7181
+ y
7182
+ }, false, dir);
7183
+ if (forward ? y > rect.bottom : y < rect.top) return EditorSelection.cursor(pos.pos, pos.assoc);
7184
+ let posCoords = view.coordsAtPos(pos.pos, pos.assoc), mid = posCoords ? (posCoords.top + posCoords.bottom) / 2 : 0;
7185
+ if (!posCoords || (forward ? mid > startY : mid < startY)) return EditorSelection.cursor(pos.pos, pos.assoc, void 0, goal);
7186
+ }
7136
7187
  }
7137
7188
  function skipAtomicRanges(atoms, pos, bias) {
7138
7189
  for (;;) {
@@ -7157,7 +7208,10 @@ function skipAtomsForSelection(atoms, sel) {
7157
7208
  } else {
7158
7209
  let from = skipAtomicRanges(atoms, range.from, -1);
7159
7210
  let to = skipAtomicRanges(atoms, range.to, 1);
7160
- if (from != range.from || to != range.to) updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to);
7211
+ if (from != range.from || to != range.to) {
7212
+ if (range.undirectional) updated = EditorSelection.undirectionalRange(range.from, range.to);
7213
+ else updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to);
7214
+ }
7161
7215
  }
7162
7216
  if (updated) {
7163
7217
  if (!ranges) ranges = sel.ranges.slice();
@@ -7185,7 +7239,8 @@ function posAtCoords(view, coords, precise, scanY) {
7185
7239
  block = view.elementAtHeight(yOffset);
7186
7240
  if (scanY == null) break;
7187
7241
  if (block.type == BlockType.Text) {
7188
- let rect = view.docView.coordsAt(scanY < 0 ? block.from : block.to, scanY);
7242
+ if (scanY < 0 ? block.to < view.viewport.from : block.from > view.viewport.to) break;
7243
+ let rect = view.docView.coordsAt(scanY < 0 ? block.from : block.to, scanY > 0 ? -1 : 1);
7189
7244
  if (rect && (scanY < 0 ? rect.top <= yOffset + docTop : rect.bottom >= yOffset + docTop)) break;
7190
7245
  }
7191
7246
  let halfLine = view.viewState.heightOracle.textHeight / 2;
@@ -7201,57 +7256,135 @@ function posAtCoords(view, coords, precise, scanY) {
7201
7256
  if (block.type != BlockType.Text) return yOffset < (block.top + block.bottom) / 2 ? new PosAssoc(block.from, 1) : new PosAssoc(block.to, -1);
7202
7257
  let line = view.docView.lineAt(block.from, 2);
7203
7258
  if (!line || line.length != block.length) line = view.docView.lineAt(block.from, -2);
7204
- return posAtCoordsInline(view, line, block.from, x, y);
7205
- }
7206
- function posAtCoordsInline(view, tile, offset, x, y) {
7207
- let closest = -1, closestRect = null;
7208
- let dxClosest = 1e9, dyClosest = 1e9;
7209
- let rowTop = y, rowBot = y;
7210
- let checkRects = (rects, index) => {
7211
- for (let i = 0; i < rects.length; i++) {
7212
- let rect = rects[i];
7213
- if (rect.top == rect.bottom) continue;
7214
- let dx = rect.left > x ? rect.left - x : rect.right < x ? x - rect.right : 0;
7215
- let dy = rect.top > y ? rect.top - y : rect.bottom < y ? y - rect.bottom : 0;
7216
- if (rect.top <= rowBot && rect.bottom >= rowTop) {
7217
- rowTop = Math.min(rect.top, rowTop);
7218
- rowBot = Math.max(rect.bottom, rowBot);
7219
- dy = 0;
7220
- }
7221
- if (closest < 0 || (dy - dyClosest || dx - dxClosest) < 0) if (closest >= 0 && dyClosest && dxClosest < dx && closestRect.top <= rowBot - 2 && closestRect.bottom >= rowTop + 2) dyClosest = 0;
7222
- else {
7223
- closest = index;
7224
- dxClosest = dx;
7225
- dyClosest = dy;
7226
- closestRect = rect;
7259
+ return new InlineCoordsScan(view, x, y, view.textDirectionAt(block.from)).scanTile(line, block.from);
7260
+ }
7261
+ var InlineCoordsScan = class {
7262
+ constructor(view, x, y, baseDir) {
7263
+ this.view = view;
7264
+ this.x = x;
7265
+ this.y = y;
7266
+ this.baseDir = baseDir;
7267
+ this.line = null;
7268
+ this.spans = null;
7269
+ }
7270
+ bidiSpansAt(pos) {
7271
+ if (!this.line || this.line.from > pos || this.line.to < pos) {
7272
+ this.line = this.view.state.doc.lineAt(pos);
7273
+ this.spans = this.view.bidiSpans(this.line);
7274
+ }
7275
+ return this;
7276
+ }
7277
+ baseDirAt(pos, side) {
7278
+ let { line, spans } = this.bidiSpansAt(pos);
7279
+ return spans[BidiSpan.find(spans, pos - line.from, -1, side)].level == this.baseDir;
7280
+ }
7281
+ dirAt(pos, side) {
7282
+ let { line, spans } = this.bidiSpansAt(pos);
7283
+ return spans[BidiSpan.find(spans, pos - line.from, -1, side)].dir;
7284
+ }
7285
+ bidiIn(from, to) {
7286
+ let { spans, line } = this.bidiSpansAt(from);
7287
+ return spans.length > 1 || spans.length && (spans[0].level != this.baseDir || spans[0].to + line.from < to);
7288
+ }
7289
+ scan(positions, getRects, recursed = false) {
7290
+ let lo = 0, hi = positions.length - 1, seen = /* @__PURE__ */ new Set();
7291
+ let bidi = this.bidiIn(positions[0], positions[hi]);
7292
+ let above, below;
7293
+ let closestI = -1, closestDx = 1e9, closestRect;
7294
+ search: while (lo < hi) {
7295
+ let dist = hi - lo, mid = lo + hi >> 1;
7296
+ adjust: if (seen.has(mid)) {
7297
+ for (let i = 1; i < dist; i++) {
7298
+ let scan = mid + i;
7299
+ if (scan >= hi) scan -= dist;
7300
+ if (!seen.has(scan)) {
7301
+ mid = scan;
7302
+ break adjust;
7303
+ }
7304
+ }
7305
+ break search;
7306
+ }
7307
+ seen.add(mid);
7308
+ let rects = getRects(mid), side = 0;
7309
+ if (rects) for (let i = 0; i < rects.length; i++) {
7310
+ let rect = rects[i];
7311
+ if (rect.width == 0 && rects.length > 1) continue;
7312
+ if (rect.bottom < this.y) {
7313
+ if (!above || above.bottom < rect.bottom) above = rect;
7314
+ side = 1;
7315
+ } else if (rect.top > this.y) {
7316
+ if (!below || below.top > rect.top) below = rect;
7317
+ side = -1;
7318
+ } else {
7319
+ let off = rect.left > this.x ? this.x - rect.left : rect.right < this.x ? this.x - rect.right : 0;
7320
+ let dx = Math.abs(off);
7321
+ if (dx < closestDx) {
7322
+ closestI = mid;
7323
+ closestDx = dx;
7324
+ closestRect = rect;
7325
+ }
7326
+ if (off) side = off < 0 == (this.baseDir == Direction.LTR) ? -1 : 1;
7327
+ }
7227
7328
  }
7329
+ if (side == -1 && (!bidi || this.baseDirAt(positions[mid], 1))) hi = mid;
7330
+ else if (side == 1 && (!bidi || this.baseDirAt(positions[mid + 1], -1))) lo = mid + 1;
7228
7331
  }
7229
- };
7230
- if (tile.isText()) {
7231
- for (let i = 0; i < tile.length;) {
7232
- let next = findClusterBreak(tile.text, i);
7233
- checkRects(textRange(tile.dom, i, next).getClientRects(), i);
7234
- if (!dxClosest && !dyClosest) break;
7235
- i = next;
7236
- }
7237
- return x > (closestRect.left + closestRect.right) / 2 == (dirAt(view, closest + offset) == Direction.LTR) ? new PosAssoc(offset + findClusterBreak(tile.text, closest), -1) : new PosAssoc(offset + closest, 1);
7238
- } else {
7332
+ if (!closestRect) {
7333
+ if (!below && !above) return {
7334
+ i: positions[0],
7335
+ after: false
7336
+ };
7337
+ let side = above && (!below || this.y - above.bottom < below.top - this.y) ? above : below;
7338
+ this.y = (side.top + side.bottom) / 2;
7339
+ return this.scan(positions, getRects, true);
7340
+ }
7341
+ if (closestDx && !recursed) {
7342
+ let { top, bottom } = closestRect;
7343
+ if (above && above.bottom > (top + top + bottom) / 3) {
7344
+ this.y = above.bottom - 1;
7345
+ return this.scan(positions, getRects, true);
7346
+ }
7347
+ if (below && below.top < (top + bottom + bottom) / 3) {
7348
+ this.y = below.top + 1;
7349
+ return this.scan(positions, getRects, true);
7350
+ }
7351
+ }
7352
+ let ltr = (bidi ? this.dirAt(positions[closestI], 1) : this.baseDir) == Direction.LTR;
7353
+ return {
7354
+ i: closestI,
7355
+ after: this.x > (closestRect.left + closestRect.right) / 2 == ltr
7356
+ };
7357
+ }
7358
+ scanText(tile, offset) {
7359
+ let positions = [];
7360
+ for (let i = 0; i < tile.length; i = findClusterBreak(tile.text, i)) positions.push(offset + i);
7361
+ positions.push(offset + tile.length);
7362
+ let scan = this.scan(positions, (i) => {
7363
+ let off = positions[i] - offset, end = positions[i + 1] - offset;
7364
+ return textRange(tile.dom, off, end).getClientRects();
7365
+ });
7366
+ return scan.after ? new PosAssoc(positions[scan.i + 1], -1) : new PosAssoc(positions[scan.i], 1);
7367
+ }
7368
+ scanTile(tile, offset) {
7239
7369
  if (!tile.length) return new PosAssoc(offset, 1);
7240
- for (let i = 0; i < tile.children.length; i++) {
7370
+ if (tile.children.length == 1) {
7371
+ let child = tile.children[0];
7372
+ if (child.isText()) return this.scanText(child, offset);
7373
+ else if (child.isComposite()) return this.scanTile(child, offset);
7374
+ }
7375
+ let positions = [offset];
7376
+ for (let i = 0, pos = offset; i < tile.children.length; i++) positions.push(pos += tile.children[i].length);
7377
+ let scan = this.scan(positions, (i) => {
7241
7378
  let child = tile.children[i];
7242
- if (child.flags & 48) continue;
7243
- checkRects((child.dom.nodeType == 1 ? child.dom : textRange(child.dom, 0, child.length)).getClientRects(), i);
7244
- if (!dxClosest && !dyClosest) break;
7245
- }
7246
- let inner = tile.children[closest], innerOff = tile.posBefore(inner, offset);
7247
- if (inner.isComposite() || inner.isText()) return posAtCoordsInline(view, inner, innerOff, Math.max(closestRect.left, Math.min(closestRect.right, x)), y);
7248
- return x > (closestRect.left + closestRect.right) / 2 == (dirAt(view, closest + offset) == Direction.LTR) ? new PosAssoc(innerOff + inner.length, -1) : new PosAssoc(innerOff, 1);
7379
+ if (child.flags & 48) return null;
7380
+ return (child.dom.nodeType == 1 ? child.dom : textRange(child.dom, 0, child.length)).getClientRects();
7381
+ });
7382
+ let child = tile.children[scan.i], pos = positions[scan.i];
7383
+ if (child.isText()) return this.scanText(child, pos);
7384
+ if (child.isComposite()) return this.scanTile(child, pos);
7385
+ return scan.after ? new PosAssoc(positions[scan.i + 1], -1) : new PosAssoc(pos, 1);
7249
7386
  }
7250
- }
7251
- function dirAt(view, pos) {
7252
- let line = view.state.doc.lineAt(pos);
7253
- return view.bidiSpans(line)[BidiSpan.find(view.bidiSpans(line), pos - line.from, -1, 1)].dir;
7254
- }
7387
+ };
7255
7388
  const LineBreakPlaceholder = "￿";
7256
7389
  var DOMReader = class {
7257
7390
  constructor(points, view) {
@@ -7360,7 +7493,7 @@ var DOMChange = class {
7360
7493
  this.bounds = null;
7361
7494
  this.text = "";
7362
7495
  this.domChanged = start > -1;
7363
- let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
7496
+ let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView, curSel = view.state.selection;
7364
7497
  if (view.state.readOnly && start > -1) this.newSel = null;
7365
7498
  else if (start > -1 && (this.bounds = domBoundsAround(view.docView.tile, start, end, 0))) {
7366
7499
  let selPoints = iHead || iAnchor ? [] : selectionPoints(view);
@@ -7370,10 +7503,10 @@ var DOMChange = class {
7370
7503
  this.newSel = selectionFromPoints(selPoints, this.bounds.from);
7371
7504
  } else {
7372
7505
  let domSel = view.observer.selectionRange;
7373
- let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || !contains(view.contentDOM, domSel.focusNode) ? view.state.selection.main.head : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
7374
- let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || !contains(view.contentDOM, domSel.anchorNode) ? view.state.selection.main.anchor : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
7506
+ let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || !contains(view.contentDOM, domSel.focusNode) ? curSel.main.head : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
7507
+ let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || !contains(view.contentDOM, domSel.anchorNode) ? curSel.main.anchor : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
7375
7508
  let vp = view.viewport;
7376
- if ((browser.ios || browser.chrome) && view.state.selection.main.empty && head != anchor && (vp.from > 0 || vp.to < view.state.doc.length)) {
7509
+ if ((browser.ios || browser.chrome) && head != anchor && Math.min(head, anchor) <= curSel.main.from && Math.max(head, anchor) >= curSel.main.to && (vp.from > 0 || vp.to < view.state.doc.length)) {
7377
7510
  let from = Math.min(head, anchor), to = Math.max(head, anchor);
7378
7511
  let offFrom = vp.from - from, offTo = vp.to - to;
7379
7512
  if ((offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length)) {
@@ -7381,8 +7514,12 @@ var DOMChange = class {
7381
7514
  anchor = view.state.doc.length;
7382
7515
  }
7383
7516
  }
7384
- if (view.inputState.composing > -1 && view.state.selection.ranges.length > 1) this.newSel = view.state.selection.replaceRange(EditorSelection.range(anchor, head));
7385
- else this.newSel = EditorSelection.single(anchor, head);
7517
+ if (view.inputState.composing > -1 && curSel.ranges.length > 1) this.newSel = curSel.replaceRange(EditorSelection.range(anchor, head));
7518
+ else if (view.lineWrapping && anchor == head && !(curSel.main.empty && curSel.main.head == head) && view.inputState.lastTouchTime > Date.now() - 100) {
7519
+ let before = view.coordsAtPos(head, -1), assoc = 0;
7520
+ if (before) assoc = view.inputState.lastTouchY <= before.bottom ? -1 : 1;
7521
+ this.newSel = EditorSelection.create([EditorSelection.cursor(head, assoc)]);
7522
+ } else this.newSel = EditorSelection.single(anchor, head);
7386
7523
  }
7387
7524
  }
7388
7525
  };
@@ -7420,7 +7557,7 @@ function domBoundsAround(tile, from, to, offset) {
7420
7557
  }
7421
7558
  function applyDOMChange(view, domChange) {
7422
7559
  let change;
7423
- let { newSel } = domChange, sel = view.state.selection.main;
7560
+ let { newSel } = domChange, { state } = view, sel = state.selection.main;
7424
7561
  let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;
7425
7562
  if (domChange.bounds) {
7426
7563
  let { from, to } = domChange.bounds;
@@ -7429,38 +7566,33 @@ function applyDOMChange(view, domChange) {
7429
7566
  preferredPos = sel.to;
7430
7567
  preferredSide = "end";
7431
7568
  }
7432
- let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);
7433
- if (diff) {
7434
- if (browser.chrome && lastKey == 13 && diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder) diff.toB--;
7569
+ let cmp = state.doc.sliceString(from, to, LineBreakPlaceholder), selEnd, diff;
7570
+ if (!sel.empty && sel.from >= from && sel.to <= to && (domChange.typeOver || cmp != domChange.text) && cmp.slice(0, sel.from - from) == domChange.text.slice(0, sel.from - from) && cmp.slice(sel.to - from) == domChange.text.slice(selEnd = domChange.text.length - (cmp.length - (sel.to - from)))) change = {
7571
+ from: sel.from,
7572
+ to: sel.to,
7573
+ insert: Text.of(domChange.text.slice(sel.from - from, selEnd).split(LineBreakPlaceholder))
7574
+ };
7575
+ else if (diff = findDiff(cmp, domChange.text, preferredPos - from, preferredSide)) {
7576
+ if (browser.chrome && lastKey == 13 && diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == "￿￿") diff.toB--;
7435
7577
  change = {
7436
7578
  from: from + diff.from,
7437
7579
  to: from + diff.toA,
7438
7580
  insert: Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder))
7439
7581
  };
7440
7582
  }
7441
- } else if (newSel && (!view.hasFocus && view.state.facet(editable) || sameSelPos(newSel, sel))) newSel = null;
7583
+ } else if (newSel && (!view.hasFocus && state.facet(editable) || sameSelPos(newSel, sel))) newSel = null;
7442
7584
  if (!change && !newSel) return false;
7443
- if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) change = {
7444
- from: sel.from,
7445
- to: sel.to,
7446
- insert: view.state.doc.slice(sel.from, sel.to)
7447
- };
7448
- else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 && /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off") {
7585
+ if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 && /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off") {
7449
7586
  if (newSel && change.insert.length == 2) newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
7450
7587
  change = {
7451
7588
  from: change.from,
7452
7589
  to: change.to,
7453
7590
  insert: Text.of([change.insert.toString().replace(".", " ")])
7454
7591
  };
7455
- } else if (change && change.from >= sel.from && change.to <= sel.to && (change.from != sel.from || change.to != sel.to) && sel.to - sel.from - (change.to - change.from) <= 4) change = {
7456
- from: sel.from,
7457
- to: sel.to,
7458
- insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))
7459
- };
7460
- else if (view.state.doc.lineAt(sel.from).to < sel.to && view.docView.lineHasWidget(sel.to) && view.inputState.insertingTextAt > Date.now() - 50) change = {
7592
+ } else if (state.doc.lineAt(sel.from).to < sel.to && view.docView.lineHasWidget(sel.to) && view.inputState.insertingTextAt > Date.now() - 50) change = {
7461
7593
  from: sel.from,
7462
7594
  to: sel.to,
7463
- insert: view.state.toText(view.inputState.insertingText)
7595
+ insert: state.toText(view.inputState.insertingText)
7464
7596
  };
7465
7597
  else if (browser.chrome && change && change.from == change.to && change.from == sel.head && change.insert.toString() == "\n " && view.lineWrapping) {
7466
7598
  if (newSel) newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
@@ -7476,7 +7608,7 @@ function applyDOMChange(view, domChange) {
7476
7608
  if (view.inputState.lastSelectionTime > Date.now() - 50) {
7477
7609
  if (view.inputState.lastSelectionOrigin == "select") scrollIntoView = true;
7478
7610
  userEvent = view.inputState.lastSelectionOrigin;
7479
- if (userEvent == "select.pointer") newSel = skipAtomsForSelection(view.state.facet(atomicRanges).map((f) => f(view)), newSel);
7611
+ if (userEvent == "select.pointer") newSel = skipAtomsForSelection(state.facet(atomicRanges).map((f) => f(view)), newSel);
7480
7612
  }
7481
7613
  view.dispatch({
7482
7614
  selection: newSel,
@@ -7620,18 +7752,16 @@ var InputState = class {
7620
7752
  this.view = view;
7621
7753
  this.lastKeyCode = 0;
7622
7754
  this.lastKeyTime = 0;
7755
+ this.touchActive = false;
7623
7756
  this.lastTouchTime = 0;
7757
+ this.lastTouchX = 0;
7758
+ this.lastTouchY = 0;
7624
7759
  this.lastFocusTime = 0;
7625
7760
  this.lastScrollTop = 0;
7626
7761
  this.lastScrollLeft = 0;
7762
+ this.lastWheelEvent = 0;
7627
7763
  this.pendingIOSKey = void 0;
7628
- /**
7629
- When enabled (>-1), tab presses are not given to key handlers,
7630
- leaving the browser's default behavior. If >0, the mode expires
7631
- at that timestamp, and any other keypress clears it.
7632
- Esc enables temporary tab focus mode for two seconds when not
7633
- otherwise handled.
7634
- */
7764
+ this.lastIOSMomentumScroll = 0;
7635
7765
  this.tabFocusMode = -1;
7636
7766
  this.lastSelectionOrigin = null;
7637
7767
  this.lastSelectionTime = 0;
@@ -7694,9 +7824,19 @@ var InputState = class {
7694
7824
  this.view.observer.delayAndroidKey(event.key, event.keyCode);
7695
7825
  return true;
7696
7826
  }
7697
- let pending;
7698
- if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey && ((pending = PendingKeys.find((key) => key.keyCode == event.keyCode)) && !event.ctrlKey || EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {
7699
- this.pendingIOSKey = pending || event;
7827
+ if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey && (PendingKeys.some((key) => key.keyCode == event.keyCode) && !event.ctrlKey || EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey)) {
7828
+ let mods = {
7829
+ ctrlKey: event.ctrlKey,
7830
+ altKey: event.altKey,
7831
+ metaKey: event.metaKey,
7832
+ shiftKey: event.shiftKey
7833
+ };
7834
+ if (mods.shiftKey && browser.ios && !/^(off|none)$/.test(this.view.contentDOM.autocapitalize) && iosVirtualKeyboardOpen(this.view.win)) mods.shiftKey = false;
7835
+ this.pendingIOSKey = {
7836
+ key: event.key,
7837
+ keyCode: event.keyCode,
7838
+ mods
7839
+ };
7700
7840
  setTimeout(() => this.flushIOSKey(), 250);
7701
7841
  return true;
7702
7842
  }
@@ -7708,7 +7848,7 @@ var InputState = class {
7708
7848
  if (!key) return false;
7709
7849
  if (key.key == "Enter" && change && change.from < change.to && /^\S+$/.test(change.insert.toString())) return false;
7710
7850
  this.pendingIOSKey = void 0;
7711
- return dispatchKey(this.view.contentDOM, key.key, key.keyCode, key instanceof KeyboardEvent ? key : void 0);
7851
+ return dispatchKey(this.view.contentDOM, key.key, key.keyCode, key.mods);
7712
7852
  }
7713
7853
  ignoreDuringComposition(event) {
7714
7854
  if (!/^key/.test(event.type) || event.synthetic) return false;
@@ -7733,6 +7873,10 @@ var InputState = class {
7733
7873
  if (this.mouseSelection) this.mouseSelection.destroy();
7734
7874
  }
7735
7875
  };
7876
+ function iosVirtualKeyboardOpen(win) {
7877
+ if (!win.visualViewport) return false;
7878
+ return win.visualViewport.height * win.visualViewport.scale / win.document.documentElement.clientHeight < .85;
7879
+ }
7736
7880
  function bindHandler(plugin, handler) {
7737
7881
  return (view, event) => {
7738
7882
  try {
@@ -7920,8 +8064,8 @@ function eventBelongsToEditor(view, event) {
7920
8064
  for (let node = event.target, tile; node != view.contentDOM; node = node.parentNode) if (!node || node.nodeType == 11 || (tile = Tile.get(node)) && tile.isWidget() && !tile.isHidden && tile.widget.ignoreEvent(event)) return false;
7921
8065
  return true;
7922
8066
  }
7923
- const handlers = /* @__PURE__ */ Object.create(null);
7924
- const observers = /* @__PURE__ */ Object.create(null);
8067
+ const handlers = /*@__PURE__*/ Object.create(null);
8068
+ const observers = /*@__PURE__*/ Object.create(null);
7925
8069
  const brokenClipboardAPI = browser.ie && browser.ie_version < 15 || browser.ios && browser.webkit_version < 604;
7926
8070
  function capturePaste(view) {
7927
8071
  let parent = view.dom.parentNode;
@@ -7976,8 +8120,13 @@ function doPaste(view, input) {
7976
8120
  });
7977
8121
  }
7978
8122
  observers.scroll = (view) => {
7979
- view.inputState.lastScrollTop = view.scrollDOM.scrollTop;
7980
- view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;
8123
+ let iState = view.inputState;
8124
+ iState.lastScrollTop = view.scrollDOM.scrollTop;
8125
+ iState.lastScrollLeft = view.scrollDOM.scrollLeft;
8126
+ if (browser.ios && !iState.touchActive) iState.lastIOSMomentumScroll = Date.now();
8127
+ };
8128
+ observers.wheel = observers.mousewheel = (view) => {
8129
+ view.inputState.lastWheelEvent = Date.now();
7981
8130
  };
7982
8131
  handlers.keydown = (view, event) => {
7983
8132
  view.inputState.setSelectionOrigin("select");
@@ -7985,12 +8134,21 @@ handlers.keydown = (view, event) => {
7985
8134
  return false;
7986
8135
  };
7987
8136
  observers.touchstart = (view, e) => {
7988
- view.inputState.lastTouchTime = Date.now();
7989
- view.inputState.setSelectionOrigin("select.pointer");
8137
+ let iState = view.inputState, touch = e.targetTouches[0];
8138
+ iState.touchActive = true;
8139
+ iState.lastTouchTime = Date.now();
8140
+ if (touch) {
8141
+ iState.lastTouchX = touch.clientX;
8142
+ iState.lastTouchY = touch.clientY;
8143
+ }
8144
+ iState.setSelectionOrigin("select.pointer");
7990
8145
  };
7991
8146
  observers.touchmove = (view) => {
7992
8147
  view.inputState.setSelectionOrigin("select.pointer");
7993
8148
  };
8149
+ observers.touchend = (view, e) => {
8150
+ view.inputState.touchActive = false;
8151
+ };
7994
8152
  handlers.mousedown = (view, event) => {
7995
8153
  view.observer.flush();
7996
8154
  if (view.inputState.lastTouchTime > Date.now() - 2e3) return false;
@@ -8023,11 +8181,13 @@ function rangeForClick(view, pos, bias, type) {
8023
8181
  let visual = view.docView.lineAt(pos, bias), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);
8024
8182
  let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to;
8025
8183
  if (to < view.state.doc.length && to == line.to) to++;
8026
- return EditorSelection.range(from, to);
8184
+ return EditorSelection.undirectionalRange(from, to);
8027
8185
  }
8028
8186
  }
8029
8187
  const BadMouseDetail = browser.ie && browser.ie_version <= 11;
8030
- let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0;
8188
+ let lastMouseDown = null;
8189
+ let lastMouseDownCount = 0;
8190
+ let lastMouseDownTime = 0;
8031
8191
  function getClickType(event) {
8032
8192
  if (!BadMouseDetail) return event.detail;
8033
8193
  let last = lastMouseDown, lastTime = lastMouseDownTime;
@@ -8057,9 +8217,9 @@ function basicMouseSelection(view, event) {
8057
8217
  if (start.pos != cur.pos && !extend) {
8058
8218
  let startRange = rangeForClick(view, start.pos, start.assoc, type);
8059
8219
  let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to);
8060
- range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from);
8220
+ range = from < range.from ? EditorSelection.range(from, to, range.assoc) : EditorSelection.range(to, from, range.assoc);
8061
8221
  }
8062
- if (extend) return startSel.replaceRange(startSel.main.extend(range.from, range.to));
8222
+ if (extend) return startSel.replaceRange(startSel.main.extend(range.from, range.to, range.assoc));
8063
8223
  else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur.pos))) return removed;
8064
8224
  else if (multiple) return startSel.addRange(range);
8065
8225
  else return EditorSelection.create([range]);
@@ -8079,7 +8239,7 @@ handlers.dragstart = (view, event) => {
8079
8239
  let tile = view.docView.tile.nearest(event.target);
8080
8240
  if (tile && tile.isWidget()) {
8081
8241
  let from = tile.posAtStart, to = from + tile.length;
8082
- if (from >= range.to || to <= range.from) range = EditorSelection.range(from, to);
8242
+ if (from >= range.to || to <= range.from) range = EditorSelection.undirectionalRange(from, to);
8083
8243
  }
8084
8244
  }
8085
8245
  let { inputState } = view;
@@ -8206,8 +8366,7 @@ function copiedRange(state) {
8206
8366
  }
8207
8367
  let lastLinewiseCopy = null;
8208
8368
  handlers.copy = handlers.cut = (view, event) => {
8209
- let domSel = getSelection(view.root);
8210
- if (domSel && !hasSelection(view.contentDOM, domSel)) return false;
8369
+ if (!hasSelection(view.contentDOM, view.observer.selectionRange)) return false;
8211
8370
  let { text, ranges, linewise } = copiedRange(view.state);
8212
8371
  if (!text && !linewise) return false;
8213
8372
  lastLinewiseCopy = linewise ? text : null;
@@ -8226,7 +8385,7 @@ handlers.copy = handlers.cut = (view, event) => {
8226
8385
  return false;
8227
8386
  }
8228
8387
  };
8229
- const isFocusChange = /* @__PURE__ */ Annotation.define();
8388
+ const isFocusChange = /*@__PURE__*/ Annotation.define();
8230
8389
  function focusChangeTransaction(state, focus) {
8231
8390
  let effects = [];
8232
8391
  for (let getEffect of state.facet(focusChangeEffect)) {
@@ -8317,7 +8476,7 @@ handlers.beforeinput = (view, event) => {
8317
8476
  if (browser.safari && event.inputType == "insertText" && view.inputState.composing >= 0) setTimeout(() => observers.compositionend(view, event), 20);
8318
8477
  return false;
8319
8478
  };
8320
- const appliedFirefoxHack = /* @__PURE__ */ new Set();
8479
+ const appliedFirefoxHack = /*@__PURE__*/ new Set();
8321
8480
  function firefoxCopyCutHack(doc) {
8322
8481
  if (!appliedFirefoxHack.has(doc)) {
8323
8482
  appliedFirefoxHack.add(doc);
@@ -8375,7 +8534,7 @@ var HeightOracle = class {
8375
8534
  }
8376
8535
  refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {
8377
8536
  let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;
8378
- let changed = Math.abs(lineHeight - this.lineHeight) > .3 || this.lineWrapping != lineWrapping || Math.abs(charWidth - this.charWidth) > .1;
8537
+ let changed = Math.abs(lineHeight - this.lineHeight) > .3 || this.lineWrapping != lineWrapping;
8379
8538
  this.lineWrapping = lineWrapping;
8380
8539
  this.lineHeight = lineHeight;
8381
8540
  this.charWidth = charWidth;
@@ -8458,7 +8617,7 @@ var BlockInfo = class BlockInfo {
8458
8617
  return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content);
8459
8618
  }
8460
8619
  };
8461
- var QueryType = /* @__PURE__ */ (function(QueryType) {
8620
+ var QueryType = /*@__PURE__*/ (function(QueryType) {
8462
8621
  QueryType[QueryType["ByPos"] = 0] = "ByPos";
8463
8622
  QueryType[QueryType["ByHeight"] = 1] = "ByHeight";
8464
8623
  QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight";
@@ -8519,20 +8678,21 @@ var HeightMap = class HeightMap {
8519
8678
  static of(nodes) {
8520
8679
  if (nodes.length == 1) return nodes[0];
8521
8680
  let i = 0, j = nodes.length, before = 0, after = 0;
8522
- for (;;) if (i == j) if (before > after * 2) {
8523
- let split = nodes[i - 1];
8524
- if (split.break) nodes.splice(--i, 1, split.left, null, split.right);
8525
- else nodes.splice(--i, 1, split.left, split.right);
8526
- j += 1 + split.break;
8527
- before -= split.size;
8528
- } else if (after > before * 2) {
8529
- let split = nodes[j];
8530
- if (split.break) nodes.splice(j, 1, split.left, null, split.right);
8531
- else nodes.splice(j, 1, split.left, split.right);
8532
- j += 2 + split.break;
8533
- after -= split.size;
8534
- } else break;
8535
- else if (before < after) {
8681
+ for (;;) if (i == j) {
8682
+ if (before > after * 2) {
8683
+ let split = nodes[i - 1];
8684
+ if (split.break) nodes.splice(--i, 1, split.left, null, split.right);
8685
+ else nodes.splice(--i, 1, split.left, split.right);
8686
+ j += 1 + split.break;
8687
+ before -= split.size;
8688
+ } else if (after > before * 2) {
8689
+ let split = nodes[j];
8690
+ if (split.break) nodes.splice(j, 1, split.left, null, split.right);
8691
+ else nodes.splice(j, 1, split.left, split.right);
8692
+ j += 2 + split.break;
8693
+ after -= split.size;
8694
+ } else break;
8695
+ } else if (before < after) {
8536
8696
  let next = nodes[i++];
8537
8697
  if (next) before += next.size;
8538
8698
  } else {
@@ -8556,7 +8716,7 @@ function replace(old, val) {
8556
8716
  return val;
8557
8717
  }
8558
8718
  HeightMap.prototype.size = 1;
8559
- const SpaceDeco = /* @__PURE__ */ Decoration.replace({});
8719
+ const SpaceDeco = /*@__PURE__*/ Decoration.replace({});
8560
8720
  var HeightMapBlock = class extends HeightMap {
8561
8721
  constructor(length, height, deco) {
8562
8722
  super(length, height);
@@ -9034,7 +9194,8 @@ var LineGapWidget = class extends WidgetType {
9034
9194
  }
9035
9195
  };
9036
9196
  var ViewState = class {
9037
- constructor(state) {
9197
+ constructor(view, state) {
9198
+ this.view = view;
9038
9199
  this.state = state;
9039
9200
  this.pixelViewport = {
9040
9201
  left: 0,
@@ -9049,10 +9210,10 @@ var ViewState = class {
9049
9210
  this.contentDOMHeight = 0;
9050
9211
  this.editorHeight = 0;
9051
9212
  this.editorWidth = 0;
9052
- this.scrollTop = 0;
9053
- this.scrolledToBottom = false;
9054
9213
  this.scaleX = 1;
9055
9214
  this.scaleY = 1;
9215
+ this.scrollOffset = 0;
9216
+ this.scrolledToBottom = false;
9056
9217
  this.scrollAnchorPos = 0;
9057
9218
  this.scrollAnchorHeight = -1;
9058
9219
  this.scaler = IdScaler;
@@ -9062,7 +9223,8 @@ var ViewState = class {
9062
9223
  this.defaultTextDirection = Direction.LTR;
9063
9224
  this.visibleRanges = [];
9064
9225
  this.mustEnforceCursorAssoc = false;
9065
- this.heightOracle = new HeightOracle(state.facet(contentAttributes).some((v) => typeof v != "function" && v.class == "cm-lineWrapping"));
9226
+ let guessWrapping = state.facet(contentAttributes).some((v) => typeof v != "function" && v.class == "cm-lineWrapping");
9227
+ this.heightOracle = new HeightOracle(guessWrapping);
9066
9228
  this.stateDeco = staticDeco(state);
9067
9229
  this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);
9068
9230
  for (let i = 0; i < 2; i++) {
@@ -9072,6 +9234,7 @@ var ViewState = class {
9072
9234
  this.updateViewportLines();
9073
9235
  this.lineGaps = this.ensureLineGaps([]);
9074
9236
  this.lineGapDeco = Decoration.set(this.lineGaps.map((gap) => gap.draw(this, false)));
9237
+ this.scrollParent = view.scrollDOM;
9075
9238
  this.computeVisibleRanges();
9076
9239
  }
9077
9240
  updateForViewport() {
@@ -9104,7 +9267,7 @@ var ViewState = class {
9104
9267
  let contentChanges = update.changedRanges;
9105
9268
  let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length)));
9106
9269
  let prevHeight = this.heightMap.height;
9107
- let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);
9270
+ let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollOffset);
9108
9271
  clearHeightChangeFlag();
9109
9272
  this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
9110
9273
  if (this.heightMap.height != prevHeight || heightChangeFlag) update.flags |= 2;
@@ -9126,12 +9289,12 @@ var ViewState = class {
9126
9289
  if (scrollTarget) this.scrollTarget = scrollTarget;
9127
9290
  if (!this.mustEnforceCursorAssoc && (update.selectionSet || update.focusChanged) && update.view.lineWrapping && update.state.selection.main.empty && update.state.selection.main.assoc && !update.state.facet(nativeSelectionHidden)) this.mustEnforceCursorAssoc = true;
9128
9291
  }
9129
- measure(view) {
9130
- let dom = view.contentDOM, style = window.getComputedStyle(dom);
9292
+ measure() {
9293
+ let { view } = this, dom = view.contentDOM, style = window.getComputedStyle(dom);
9131
9294
  let oracle = this.heightOracle;
9132
9295
  let whiteSpace = style.whiteSpace;
9133
9296
  this.defaultTextDirection = style.direction == "rtl" ? Direction.RTL : Direction.LTR;
9134
- let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace) || this.mustMeasureContent;
9297
+ let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace) || this.mustMeasureContent === "refresh";
9135
9298
  let domRect = dom.getBoundingClientRect();
9136
9299
  let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;
9137
9300
  this.contentDOMHeight = domRect.height;
@@ -9158,12 +9321,18 @@ var ViewState = class {
9158
9321
  this.editorWidth = view.scrollDOM.clientWidth;
9159
9322
  result |= 16;
9160
9323
  }
9161
- let scrollTop = view.scrollDOM.scrollTop * this.scaleY;
9162
- if (this.scrollTop != scrollTop) {
9324
+ let scrollParent = scrollableParents(this.view.contentDOM, false).y;
9325
+ if (scrollParent != this.scrollParent) {
9326
+ this.scrollParent = scrollParent;
9327
+ this.scrollAnchorHeight = -1;
9328
+ this.scrollOffset = 0;
9329
+ }
9330
+ let scrollOffset = this.getScrollOffset();
9331
+ if (this.scrollOffset != scrollOffset) {
9163
9332
  this.scrollAnchorHeight = -1;
9164
- this.scrollTop = scrollTop;
9333
+ this.scrollOffset = scrollOffset;
9165
9334
  }
9166
- this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);
9335
+ this.scrolledToBottom = isScrolledToBottom(this.scrollParent || view.win);
9167
9336
  let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);
9168
9337
  let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
9169
9338
  this.pixelViewport = pixelViewport;
@@ -9233,7 +9402,7 @@ var ViewState = class {
9233
9402
  if (scrollTarget.y == "center") topPos = (block.top + block.bottom) / 2 - viewHeight / 2;
9234
9403
  else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from) topPos = block.top;
9235
9404
  else topPos = block.bottom - viewHeight;
9236
- viewport = new Viewport(map.lineAt(topPos - 1e3 / 2, QueryType.ByHeight, oracle, 0, 0).from, map.lineAt(topPos + viewHeight + 1e3 / 2, QueryType.ByHeight, oracle, 0, 0).to);
9405
+ viewport = new Viewport(map.lineAt(topPos - 500, QueryType.ByHeight, oracle, 0, 0).from, map.lineAt(topPos + viewHeight + 500, QueryType.ByHeight, oracle, 0, 0).to);
9237
9406
  }
9238
9407
  }
9239
9408
  return viewport;
@@ -9247,7 +9416,7 @@ var ViewState = class {
9247
9416
  let { top } = this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0);
9248
9417
  let { bottom } = this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0);
9249
9418
  let { visibleTop, visibleBottom } = this;
9250
- return (from == 0 || top <= visibleTop - Math.max(10, Math.min(-bias, 250))) && (to == this.state.doc.length || bottom >= visibleBottom + Math.max(10, Math.min(bias, 250))) && top > visibleTop - 2 * 1e3 && bottom < visibleBottom + 2 * 1e3;
9419
+ return (from == 0 || top <= visibleTop - Math.max(10, Math.min(-bias, 250))) && (to == this.state.doc.length || bottom >= visibleBottom + Math.max(10, Math.min(bias, 250))) && top > visibleTop - 2e3 && bottom < visibleBottom + 2e3;
9251
9420
  }
9252
9421
  mapLineGaps(gaps, changes) {
9253
9422
  if (!gaps.length || changes.empty) return gaps;
@@ -9370,9 +9539,12 @@ var ViewState = class {
9370
9539
  lineBlockAtHeight(height) {
9371
9540
  return height >= this.viewportLines[0].top && height <= this.viewportLines[this.viewportLines.length - 1].bottom && this.viewportLines.find((l) => l.top <= height && l.bottom >= height) || scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType.ByHeight, this.heightOracle, 0, 0), this.scaler);
9372
9541
  }
9373
- scrollAnchorAt(scrollTop) {
9374
- let block = this.lineBlockAtHeight(scrollTop + 8);
9375
- return block.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block : this.viewportLines[0];
9542
+ getScrollOffset() {
9543
+ return (this.scrollParent == this.view.scrollDOM ? this.scrollParent.scrollTop : (this.scrollParent ? this.scrollParent.getBoundingClientRect().top : 0) - this.view.contentDOM.getBoundingClientRect().top) * this.scaleY;
9544
+ }
9545
+ scrollAnchorAt(scrollOffset) {
9546
+ let block = this.lineBlockAtHeight(scrollOffset + 8);
9547
+ return block.from >= this.viewport.from || this.viewportLines[0].top - scrollOffset > 200 ? block : this.viewportLines[0];
9376
9548
  }
9377
9549
  elementAtHeight(height) {
9378
9550
  return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler);
@@ -9510,9 +9682,11 @@ function scaleBlock(block, scaler) {
9510
9682
  let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom);
9511
9683
  return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block._content) ? block._content.map((b) => scaleBlock(b, scaler)) : block._content);
9512
9684
  }
9513
- const theme = /* @__PURE__ */ Facet.define({ combine: (strs) => strs.join(" ") });
9514
- const darkTheme = /* @__PURE__ */ Facet.define({ combine: (values) => values.indexOf(true) > -1 });
9515
- const baseThemeID = /* @__PURE__ */ StyleModule.newName(), baseLightID = /* @__PURE__ */ StyleModule.newName(), baseDarkID = /* @__PURE__ */ StyleModule.newName();
9685
+ const theme = /*@__PURE__*/ Facet.define({ combine: (strs) => strs.join(" ") });
9686
+ const darkTheme = /*@__PURE__*/ Facet.define({ combine: (values) => values.indexOf(true) > -1 });
9687
+ const baseThemeID = /*@__PURE__*/ StyleModule.newName();
9688
+ const baseLightID = /*@__PURE__*/ StyleModule.newName();
9689
+ const baseDarkID = /*@__PURE__*/ StyleModule.newName();
9516
9690
  const lightDarkIDs = {
9517
9691
  "&light": "." + baseLightID,
9518
9692
  "&dark": "." + baseDarkID
@@ -9526,7 +9700,7 @@ function buildTheme(main, spec, scopes) {
9526
9700
  }) : main + " " + sel;
9527
9701
  } });
9528
9702
  }
9529
- const baseTheme$1 = /* @__PURE__ */ buildTheme("." + baseThemeID, {
9703
+ const baseTheme$1 = /*@__PURE__*/ buildTheme("." + baseThemeID, {
9530
9704
  "&": {
9531
9705
  position: "relative !important",
9532
9706
  boxSizing: "border-box",
@@ -9572,6 +9746,7 @@ const baseTheme$1 = /* @__PURE__ */ buildTheme("." + baseThemeID, {
9572
9746
  padding: "0 2px 0 6px"
9573
9747
  },
9574
9748
  ".cm-layer": {
9749
+ userSelect: "none",
9575
9750
  position: "absolute",
9576
9751
  left: 0,
9577
9752
  top: 0,
@@ -9601,6 +9776,21 @@ const baseTheme$1 = /* @__PURE__ */ buildTheme("." + baseThemeID, {
9601
9776
  },
9602
9777
  ".cm-cursor": { display: "none" },
9603
9778
  "&dark .cm-cursor": { borderLeftColor: "#ddd" },
9779
+ ".cm-selectionHandle": {
9780
+ backgroundColor: "currentColor",
9781
+ width: "1.5px"
9782
+ },
9783
+ ".cm-selectionHandle-start::before, .cm-selectionHandle-end::before": {
9784
+ content: "\"\"",
9785
+ backgroundColor: "inherit",
9786
+ borderRadius: "50%",
9787
+ width: "8px",
9788
+ height: "8px",
9789
+ position: "absolute",
9790
+ left: "-3.25px"
9791
+ },
9792
+ ".cm-selectionHandle-start::before": { top: "-8px" },
9793
+ ".cm-selectionHandle-end::before": { bottom: "-8px" },
9604
9794
  ".cm-dropCursor": { position: "absolute" },
9605
9795
  "&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor": { display: "block" },
9606
9796
  ".cm-iso": { unicodeBidi: "isolate" },
@@ -9661,6 +9851,8 @@ const baseTheme$1 = /* @__PURE__ */ buildTheme("." + baseThemeID, {
9661
9851
  backgroundColor: "#f5f5f5",
9662
9852
  color: "black"
9663
9853
  },
9854
+ ".cm-panels-top": { top: "0" },
9855
+ ".cm-panels-bottom": { bottom: "0" },
9664
9856
  "&light .cm-panels-top": { borderBottom: "1px solid #ddd" },
9665
9857
  "&light .cm-panels-bottom": { borderTop: "1px solid #ddd" },
9666
9858
  "&dark .cm-panels": {
@@ -10041,18 +10233,20 @@ var DOMObserver = class {
10041
10233
  }
10042
10234
  addWindowListeners(win) {
10043
10235
  win.addEventListener("resize", this.onResize);
10044
- if (this.printQuery) if (this.printQuery.addEventListener) this.printQuery.addEventListener("change", this.onPrint);
10045
- else this.printQuery.addListener(this.onPrint);
10046
- else win.addEventListener("beforeprint", this.onPrint);
10236
+ if (this.printQuery) {
10237
+ if (this.printQuery.addEventListener) this.printQuery.addEventListener("change", this.onPrint);
10238
+ else this.printQuery.addListener(this.onPrint);
10239
+ } else win.addEventListener("beforeprint", this.onPrint);
10047
10240
  win.addEventListener("scroll", this.onScroll);
10048
10241
  win.document.addEventListener("selectionchange", this.onSelectionChange);
10049
10242
  }
10050
10243
  removeWindowListeners(win) {
10051
10244
  win.removeEventListener("scroll", this.onScroll);
10052
10245
  win.removeEventListener("resize", this.onResize);
10053
- if (this.printQuery) if (this.printQuery.removeEventListener) this.printQuery.removeEventListener("change", this.onPrint);
10054
- else this.printQuery.removeListener(this.onPrint);
10055
- else win.removeEventListener("beforeprint", this.onPrint);
10246
+ if (this.printQuery) {
10247
+ if (this.printQuery.removeEventListener) this.printQuery.removeEventListener("change", this.onPrint);
10248
+ else this.printQuery.removeListener(this.onPrint);
10249
+ } else win.removeEventListener("beforeprint", this.onPrint);
10056
10250
  win.document.removeEventListener("selectionchange", this.onSelectionChange);
10057
10251
  }
10058
10252
  update(update) {
@@ -10215,7 +10409,6 @@ var EditContextManager = class {
10215
10409
  };
10216
10410
  for (let event in this.handlers) context.addEventListener(event, this.handlers[event]);
10217
10411
  this.measureReq = { read: (view) => {
10218
- this.editContext.updateControlBounds(view.contentDOM.getBoundingClientRect());
10219
10412
  let sel = getSelection(view.root);
10220
10413
  if (sel && sel.rangeCount) this.editContext.updateSelectionBounds(sel.getRangeAt(0).getBoundingClientRect());
10221
10414
  } };
@@ -10225,14 +10418,16 @@ var EditContextManager = class {
10225
10418
  update.changes.iterChanges((fromA, toA, _fromB, _toB, insert) => {
10226
10419
  if (abort) return;
10227
10420
  let dLen = insert.length - (toA - fromA);
10228
- if (pending && toA >= pending.to) if (pending.from == fromA && pending.to == toA && pending.insert.eq(insert)) {
10229
- pending = this.pendingContextChange = null;
10230
- off += dLen;
10231
- this.to += dLen;
10232
- return;
10233
- } else {
10234
- pending = null;
10235
- this.revertPending(update.state);
10421
+ if (pending && toA >= pending.to) {
10422
+ if (pending.from == fromA && pending.to == toA && pending.insert.eq(insert)) {
10423
+ pending = this.pendingContextChange = null;
10424
+ off += dLen;
10425
+ this.to += dLen;
10426
+ return;
10427
+ } else {
10428
+ pending = null;
10429
+ this.revertPending(update.state);
10430
+ }
10236
10431
  }
10237
10432
  fromA += off;
10238
10433
  toA += off;
@@ -10286,7 +10481,7 @@ var EditContextManager = class {
10286
10481
  }
10287
10482
  rangeIsValid(state) {
10288
10483
  let { head } = state.selection.main;
10289
- return !(this.from > 0 && head - this.from < 500 || this.to < state.doc.length && this.to - head < 500 || this.to - this.from > 1e4 * 3);
10484
+ return !(this.from > 0 && head - this.from < 500 || this.to < state.doc.length && this.to - head < 500 || this.to - this.from > 3e4);
10290
10485
  }
10291
10486
  toEditorPos(contextPos, clipLen = this.to - this.from) {
10292
10487
  contextPos = Math.min(contextPos, clipLen);
@@ -10412,7 +10607,7 @@ var EditorView = class EditorView {
10412
10607
  this.dispatchTransactions = config.dispatchTransactions || dispatch && ((trs) => trs.forEach((tr) => dispatch(tr, this))) || ((trs) => this.update(trs));
10413
10608
  this.dispatch = this.dispatch.bind(this);
10414
10609
  this._root = config.root || getRoot(config.parent) || document;
10415
- this.viewState = new ViewState(config.state || EditorState.create(config));
10610
+ this.viewState = new ViewState(this, config.state || EditorState.create(config));
10416
10611
  if (config.scrollTo && config.scrollTo.is(scrollIntoView)) this.viewState.scrollTarget = config.scrollTo.value.clip(this.viewState.state);
10417
10612
  this.plugins = this.state.facet(viewPlugin).map((spec) => new PluginInstance(spec));
10418
10613
  for (let plugin of this.plugins) plugin.update(this);
@@ -10425,7 +10620,7 @@ var EditorView = class EditorView {
10425
10620
  this.updateState = 0;
10426
10621
  this.requestMeasure();
10427
10622
  if ((_a = document.fonts) === null || _a === void 0 ? void 0 : _a.ready) document.fonts.ready.then(() => {
10428
- this.viewState.mustMeasureContent = true;
10623
+ this.viewState.mustMeasureContent = "refresh";
10429
10624
  this.requestMeasure();
10430
10625
  });
10431
10626
  }
@@ -10478,7 +10673,8 @@ var EditorView = class EditorView {
10478
10673
  if (scrollTarget) scrollTarget = scrollTarget.map(tr.changes);
10479
10674
  if (tr.scrollIntoView) {
10480
10675
  let { main } = tr.state.selection;
10481
- scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));
10676
+ let { x, y } = this.state.facet(EditorView.cursorScrollMargin);
10677
+ scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1), "nearest", "nearest", y, x);
10482
10678
  }
10483
10679
  for (let e of tr.effects) if (e.is(scrollIntoView)) scrollTarget = e.value.clip(this.state);
10484
10680
  }
@@ -10528,7 +10724,7 @@ var EditorView = class EditorView {
10528
10724
  let hadFocus = this.hasFocus;
10529
10725
  try {
10530
10726
  for (let plugin of this.plugins) plugin.destroy(this);
10531
- this.viewState = new ViewState(newState);
10727
+ this.viewState = new ViewState(this, newState);
10532
10728
  this.plugins = newState.facet(viewPlugin).map((spec) => new PluginInstance(spec));
10533
10729
  this.pluginMap.clear();
10534
10730
  for (let plugin of this.plugins) plugin.update(this);
@@ -10588,22 +10784,24 @@ var EditorView = class EditorView {
10588
10784
  this.measureScheduled = 0;
10589
10785
  if (flush) this.observer.forceFlush();
10590
10786
  let updated = null;
10591
- let sDOM = this.scrollDOM, scrollTop = sDOM.scrollTop * this.scaleY;
10787
+ let scroll = this.viewState.scrollParent, scrollOffset = this.viewState.getScrollOffset();
10592
10788
  let { scrollAnchorPos, scrollAnchorHeight } = this.viewState;
10593
- if (Math.abs(scrollTop - this.viewState.scrollTop) > 1) scrollAnchorHeight = -1;
10789
+ if (Math.abs(scrollOffset - this.viewState.scrollOffset) > 1) scrollAnchorHeight = -1;
10594
10790
  this.viewState.scrollAnchorHeight = -1;
10595
10791
  try {
10596
10792
  for (let i = 0;; i++) {
10597
- if (scrollAnchorHeight < 0) if (isScrolledToBottom(sDOM)) {
10598
- scrollAnchorPos = -1;
10599
- scrollAnchorHeight = this.viewState.heightMap.height;
10600
- } else {
10601
- let block = this.viewState.scrollAnchorAt(scrollTop);
10602
- scrollAnchorPos = block.from;
10603
- scrollAnchorHeight = block.top;
10793
+ if (scrollAnchorHeight < 0) {
10794
+ if (isScrolledToBottom(scroll || this.win)) {
10795
+ scrollAnchorPos = -1;
10796
+ scrollAnchorHeight = this.viewState.heightMap.height;
10797
+ } else {
10798
+ let block = this.viewState.scrollAnchorAt(scrollOffset);
10799
+ scrollAnchorPos = block.from;
10800
+ scrollAnchorHeight = block.top;
10801
+ }
10604
10802
  }
10605
10803
  this.updateState = 1;
10606
- let changed = this.viewState.measure(this);
10804
+ let changed = this.viewState.measure();
10607
10805
  if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null) break;
10608
10806
  if (i > 5) {
10609
10807
  console.warn(this.measureRequests.length ? "Measure loop restarted more than 5 times" : "Viewport failed to stabilize");
@@ -10639,18 +10837,21 @@ var EditorView = class EditorView {
10639
10837
  }
10640
10838
  if (redrawn) this.docView.updateSelection(true);
10641
10839
  if (!update.viewportChanged && this.measureRequests.length == 0) {
10642
- if (this.viewState.editorHeight) if (this.viewState.scrollTarget) {
10643
- this.docView.scrollIntoView(this.viewState.scrollTarget);
10644
- this.viewState.scrollTarget = null;
10645
- scrollAnchorHeight = -1;
10646
- continue;
10647
- } else {
10648
- let diff = (scrollAnchorPos < 0 ? this.viewState.heightMap.height : this.viewState.lineBlockAt(scrollAnchorPos).top) - scrollAnchorHeight;
10649
- if (diff > 1 || diff < -1) {
10650
- scrollTop = scrollTop + diff;
10651
- sDOM.scrollTop = scrollTop / this.scaleY;
10840
+ if (this.viewState.editorHeight) {
10841
+ if (this.viewState.scrollTarget) {
10842
+ this.docView.scrollIntoView(this.viewState.scrollTarget);
10843
+ this.viewState.scrollTarget = null;
10652
10844
  scrollAnchorHeight = -1;
10653
10845
  continue;
10846
+ } else {
10847
+ let diff = ((scrollAnchorPos < 0 ? this.viewState.heightMap.height : this.viewState.lineBlockAt(scrollAnchorPos).top) - scrollAnchorHeight) / this.scaleY;
10848
+ if ((diff > 1 || diff < -1) && !(browser.ios && this.inputState.lastIOSMomentumScroll > Date.now() - 100) && (scroll == this.scrollDOM || this.hasFocus || Math.max(this.inputState.lastWheelEvent, this.inputState.lastTouchTime) > Date.now() - 100)) {
10849
+ scrollOffset = scrollOffset + diff;
10850
+ if (scroll) scroll.scrollTop += diff;
10851
+ else this.win.scrollBy(0, diff);
10852
+ scrollAnchorHeight = -1;
10853
+ continue;
10854
+ }
10654
10855
  }
10655
10856
  }
10656
10857
  break;
@@ -10922,11 +11123,9 @@ var EditorView = class EditorView {
10922
11123
  */
10923
11124
  coordsAtPos(pos, side = 1) {
10924
11125
  this.readMeasured();
10925
- let rect = this.docView.coordsAt(pos, side);
10926
- if (!rect || rect.left == rect.right) return rect;
10927
11126
  let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line);
10928
11127
  let span = order[BidiSpan.find(order, pos - line.from, -1, side)];
10929
- return flattenRect(rect, span.dir == Direction.LTR == side > 0);
11128
+ return this.docView.coordsAt(pos, side, span.dir == Direction.RTL);
10930
11129
  }
10931
11130
  /**
10932
11131
  Return the rectangle around a given character. If `pos` does not
@@ -11052,7 +11251,8 @@ var EditorView = class EditorView {
11052
11251
  cause it to scroll the given position or range into view.
11053
11252
  */
11054
11253
  static scrollIntoView(pos, options = {}) {
11055
- return scrollIntoView.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin));
11254
+ var _a, _b, _c, _d;
11255
+ return scrollIntoView.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, (_a = options.y) !== null && _a !== void 0 ? _a : "nearest", (_b = options.x) !== null && _b !== void 0 ? _b : "nearest", (_c = options.yMargin) !== null && _c !== void 0 ? _c : 5, (_d = options.xMargin) !== null && _d !== void 0 ? _d : 5));
11056
11256
  }
11057
11257
  /**
11058
11258
  Return an effect that resets the editor to its current (at the
@@ -11115,7 +11315,7 @@ var EditorView = class EditorView {
11115
11315
  }
11116
11316
  /**
11117
11317
  Create a theme extension. The first argument can be a
11118
- [`style-mod`](https://github.com/marijnh/style-mod#documentation)
11318
+ [`style-mod`](https://code.haverbeke.berlin/marijn/style-mod#documentation)
11119
11319
  style spec providing the styles for the theme. These will be
11120
11320
  prefixed with a generated class for the style.
11121
11321
 
@@ -11160,7 +11360,7 @@ var EditorView = class EditorView {
11160
11360
  };
11161
11361
  /**
11162
11362
  Facet to add a [style
11163
- module](https://github.com/marijnh/style-mod#documentation) to
11363
+ module](https://code.haverbeke.berlin/marijn/style-mod#documentation) to
11164
11364
  an editor view. The view will ensure that the module is
11165
11365
  mounted in its [document
11166
11366
  root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root).
@@ -11307,11 +11507,27 @@ supported.)
11307
11507
  */
11308
11508
  EditorView.bidiIsolatedRanges = bidiIsolatedRanges;
11309
11509
  /**
11510
+ Can be used to specify the distance that scrolling cursor into
11511
+ view keeps it away from the sides of the editor, either as a
11512
+ single pixel number or two different values for the different
11513
+ axes. Defaults to 5 pixels on both axes.
11514
+ */
11515
+ EditorView.cursorScrollMargin = /*@__PURE__*/ Facet.define({ combine: (inputs) => {
11516
+ let x = 5, y = 5;
11517
+ for (let i of inputs) if (typeof i == "number") x = y = i;
11518
+ else ({x, y} = i);
11519
+ return {
11520
+ x,
11521
+ y
11522
+ };
11523
+ } });
11524
+ /**
11310
11525
  Facet that allows extensions to provide additional scroll
11311
11526
  margins (space around the sides of the scrolling element that
11312
11527
  should be considered invisible). This can be useful when the
11313
11528
  plugin introduces elements that cover part of that element (for
11314
- example a horizontally fixed gutter).
11529
+ example a horizontally fixed gutter). Not to be confused with
11530
+ [`cursorScrollMargin`](https://codemirror.net/6/docs/ref/#view.EditorView^cursorScrollMargin).
11315
11531
  */
11316
11532
  EditorView.scrollMargins = scrollMargins;
11317
11533
  /**
@@ -11326,7 +11542,7 @@ Provides a Content Security Policy nonce to use when creating
11326
11542
  the style sheets for the editor. Holds the empty string when no
11327
11543
  nonce has been provided.
11328
11544
  */
11329
- EditorView.cspNonce = /* @__PURE__ */ Facet.define({ combine: (values) => values.length ? values[0] : "" });
11545
+ EditorView.cspNonce = /*@__PURE__*/ Facet.define({ combine: (values) => values.length ? values[0] : "" });
11330
11546
  /**
11331
11547
  Facet that provides additional DOM attributes for the editor's
11332
11548
  editable DOM element.
@@ -11341,7 +11557,7 @@ EditorView.editorAttributes = editorAttributes;
11341
11557
  An extension that enables line wrapping in the editor (by
11342
11558
  setting CSS `white-space` to `pre-wrap` in the content).
11343
11559
  */
11344
- EditorView.lineWrapping = /* @__PURE__ */ EditorView.contentAttributes.of({ "class": "cm-lineWrapping" });
11560
+ EditorView.lineWrapping = /*@__PURE__*/ EditorView.contentAttributes.of({ "class": "cm-lineWrapping" });
11345
11561
  /**
11346
11562
  State effect used to include screen reader announcements in a
11347
11563
  transaction. These will be added to the DOM in a visually hidden
@@ -11350,7 +11566,7 @@ describe effects that are visually obvious but may not be
11350
11566
  noticed by screen reader users (such as moving to the next
11351
11567
  search match).
11352
11568
  */
11353
- EditorView.announce = /* @__PURE__ */ StateEffect.define();
11569
+ EditorView.announce = /*@__PURE__*/ StateEffect.define();
11354
11570
  const MaxBidiLine = 4096;
11355
11571
  const BadMeasure = {};
11356
11572
  var CachedOrder = class CachedOrder {
@@ -11379,8 +11595,9 @@ function attrsFromFacet(view, facet, base) {
11379
11595
  }
11380
11596
  return base;
11381
11597
  }
11382
- const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key";
11383
- const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g";
11598
+ browser.mac || browser.windows || browser.linux;
11599
+ browser.gecko && browser.gecko_version;
11600
+ /x/.unicode;
11384
11601
  /**
11385
11602
  A gutter marker represents a bit of information attached to a line
11386
11603
  in a specific gutter. Your own custom markers have to extend this
@@ -11410,7 +11627,6 @@ GutterMarker.prototype.toDOM = void 0;
11410
11627
  GutterMarker.prototype.mapMode = MapMode.TrackBefore;
11411
11628
  GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1;
11412
11629
  GutterMarker.prototype.point = true;
11413
-
11414
11630
  //#endregion
11415
11631
  //#region src/components/editor/use-format-code.ts
11416
11632
  const DEFAULT_PRETTIER_OPTIONS = {
@@ -11442,7 +11658,6 @@ const useFormatCode = ({ fragment, prettierOptions } = {}) => {
11442
11658
  return formatted;
11443
11659
  }, [prettierConfig, fragment]);
11444
11660
  };
11445
-
11446
11661
  //#endregion
11447
11662
  //#region src/components/editor/core.tsx
11448
11663
  const Core = ({ value, theme, height, className, prettierOptions, fragment, raw, onChange, onSave: _onSave, onError, ...props }) => {
@@ -11486,7 +11701,8 @@ const Core = ({ value, theme, height, className, prettierOptions, fragment, raw,
11486
11701
  const onKeyDown = useCallback((e) => {
11487
11702
  if ((e.metaKey || e.ctrlKey) && e.key === "s") {
11488
11703
  e.preventDefault();
11489
- onSave(editorRef.current?.view?.state.doc.toString() || value);
11704
+ const currentValue = editorRef.current?.view?.state.doc.toString() || value;
11705
+ onSave(currentValue);
11490
11706
  }
11491
11707
  }, [onSave, value]);
11492
11708
  return /* @__PURE__ */ jsx("div", {
@@ -11506,7 +11722,6 @@ const Core = ({ value, theme, height, className, prettierOptions, fragment, raw,
11506
11722
  })
11507
11723
  });
11508
11724
  };
11509
-
11510
11725
  //#endregion
11511
11726
  //#region src/components/editor/tiptap.tsx
11512
11727
  const Tiptap = ({ value = "", placeholder = "Enter text...", className, onChange }) => {
@@ -11527,11 +11742,10 @@ const Tiptap = ({ value = "", placeholder = "Enter text...", className, onChange
11527
11742
  py-2`, "prose prose-sm max-w-none text-sm text-gray-800", "[&_.tiptap]:outline-none", "[&_.tiptap_p.is-editor-empty:first-child::before]:pointer-events-none", "[&_.tiptap_p.is-editor-empty:first-child::before]:float-left", "[&_.tiptap_p.is-editor-empty:first-child::before]:h-0", "[&_.tiptap_p.is-editor-empty:first-child::before]:text-gray-400", "[&_.tiptap_p.is-editor-empty:first-child::before]:content-[attr(data-placeholder)]", className)
11528
11743
  });
11529
11744
  };
11530
-
11531
11745
  //#endregion
11532
11746
  //#region src/components/dnd/panel/selection.ts
11533
- var import_lib$1 = /* @__PURE__ */ __toESM(require_lib$1());
11534
11747
  var import_lib = require_lib();
11748
+ var import_lib$1 = /* @__PURE__ */ __toESM(require_lib$1(), 1);
11535
11749
  const removeIndices = (items, indices) => {
11536
11750
  return items.filter((_, index) => !indices.has(index));
11537
11751
  };
@@ -11557,7 +11771,6 @@ const moveSelectedIndices = (items, indices, direction) => {
11557
11771
  indices: nextIndices
11558
11772
  };
11559
11773
  };
11560
-
11561
11774
  //#endregion
11562
11775
  //#region src/components/dnd/panel/items.tsx
11563
11776
  const BulkActionsBar = ({ count, onDuplicate, onMoveUp, onMoveDown, onDelete, onClear }) => {
@@ -11634,7 +11847,8 @@ const Items = ({ value, render, onChange, onChildChange }) => {
11634
11847
  if (!import_lib$1.isObjectProperty(prop) || !import_lib$1.isIdentifier(prop.key) || !import_lib$1.isJSXElement(prop.value)) return;
11635
11848
  const propertyName = prop.key.name;
11636
11849
  try {
11637
- const nodes = extract(generateCode(prop.value));
11850
+ const jsxCode = generateCode(prop.value);
11851
+ const nodes = extract(jsxCode);
11638
11852
  const bindings = [];
11639
11853
  const bindingContainer = nodes.find((node) => node.bindings?.some((b) => b.property === "children"));
11640
11854
  if (bindingContainer) bindings.push(bindingContainer);
@@ -11693,7 +11907,7 @@ const Items = ({ value, render, onChange, onChildChange }) => {
11693
11907
  const nextElements = removeIndices(allElements, indices);
11694
11908
  onChange?.(generateCode(import_lib$1.arrayExpression(nextElements)));
11695
11909
  };
11696
- const deletePrimitive = (index) => deleteSelectedPrimitives(new Set([index]));
11910
+ const deletePrimitive = (index) => deleteSelectedPrimitives(/* @__PURE__ */ new Set([index]));
11697
11911
  const addPrimitive = () => {
11698
11912
  const first = primitiveItems[0];
11699
11913
  if (!first) return;
@@ -11767,10 +11981,11 @@ const Items = ({ value, render, onChange, onChildChange }) => {
11767
11981
  };
11768
11982
  const deleteSelectedItems = (indices) => {
11769
11983
  if (objectItems.length - indices.size < 1) return;
11770
- const nextValue = arrayExpressionToCode(removeIndices(objectItems, indices).map((item) => item.originalElement));
11984
+ const nextItems = removeIndices(objectItems, indices);
11985
+ const nextValue = arrayExpressionToCode(nextItems.map((item) => item.originalElement));
11771
11986
  onChange?.(nextValue);
11772
11987
  };
11773
- const deleteItem = (index) => deleteSelectedItems(new Set([index]));
11988
+ const deleteItem = (index) => deleteSelectedItems(/* @__PURE__ */ new Set([index]));
11774
11989
  const cloneObjectItemElement = (source) => {
11775
11990
  const clonedElement = clone(source.originalElement);
11776
11991
  clonedElement.properties.forEach((prop) => {
@@ -12041,7 +12256,6 @@ const Items = ({ value, render, onChange, onChildChange }) => {
12041
12256
  ]
12042
12257
  });
12043
12258
  };
12044
-
12045
12259
  //#endregion
12046
12260
  //#region src/components/dnd/panel/children.tsx
12047
12261
  const Children = ({ value, onChange, onNodeChange }) => {
@@ -12071,9 +12285,10 @@ const Children = ({ value, onChange, onNodeChange }) => {
12071
12285
  const nextItems = removeIndices(items, indices);
12072
12286
  onChange?.(JSON.stringify(nextItems));
12073
12287
  };
12074
- const deleteItem = (index) => deleteSelectedItems(new Set([index]));
12288
+ const deleteItem = (index) => deleteSelectedItems(/* @__PURE__ */ new Set([index]));
12075
12289
  const addItem = () => {
12076
- const newItem = cloneDataAttrNode(items[0] || createDefaultItem());
12290
+ const template = items[0] || createDefaultItem();
12291
+ const newItem = cloneDataAttrNode(template);
12077
12292
  const nextItems = [...items, newItem];
12078
12293
  onChange?.(JSON.stringify(nextItems));
12079
12294
  };
@@ -12234,7 +12449,6 @@ const Children = ({ value, onChange, onNodeChange }) => {
12234
12449
  ]
12235
12450
  });
12236
12451
  };
12237
-
12238
12452
  //#endregion
12239
12453
  //#region src/components/dnd/panel/icon-map.ts
12240
12454
  const ICON_MAP = {
@@ -12276,7 +12490,6 @@ const ICON_MAP = {
12276
12490
  User,
12277
12491
  X
12278
12492
  };
12279
-
12280
12493
  //#endregion
12281
12494
  //#region src/components/dnd/panel/field.tsx
12282
12495
  const isColorProperty = (propertyName) => {
@@ -12608,7 +12821,6 @@ const Field = ({ binding, id, value, onChange }) => {
12608
12821
  children: validationError
12609
12822
  })] });
12610
12823
  };
12611
-
12612
12824
  //#endregion
12613
12825
  //#region src/components/dnd/panel/node.tsx
12614
12826
  const Node = ({ data, onChange }) => {
@@ -12647,21 +12859,21 @@ const Node = ({ data, onChange }) => {
12647
12859
  })
12648
12860
  });
12649
12861
  };
12650
-
12651
12862
  //#endregion
12652
12863
  //#region src/components/dnd/panel/panel.tsx
12653
12864
  const Panel = ({ item, onChange, onDelete }) => {
12865
+ const code = item?.code;
12654
12866
  const { dataAttrNodes, updatedCode, parseError } = useMemo(() => {
12655
- if (!item?.code) return {
12867
+ if (!code) return {
12656
12868
  dataAttrNodes: [],
12657
12869
  updatedCode: "",
12658
12870
  parseError: false
12659
12871
  };
12660
12872
  try {
12661
- const updatedCode = fillIds(item.code);
12873
+ const updatedCode = fillIds(code);
12662
12874
  return {
12663
12875
  dataAttrNodes: extract(updatedCode).filter((node) => node.tagName !== "section"),
12664
- updatedCode: updatedCode !== item.code ? updatedCode : item.code,
12876
+ updatedCode: updatedCode !== code ? updatedCode : code,
12665
12877
  parseError: false
12666
12878
  };
12667
12879
  } catch (e) {
@@ -12672,7 +12884,7 @@ const Panel = ({ item, onChange, onDelete }) => {
12672
12884
  parseError: true
12673
12885
  };
12674
12886
  }
12675
- }, [item?.code]);
12887
+ }, [code]);
12676
12888
  useEffect(() => {
12677
12889
  if (parseError) Toast.error("Failed to parse this section", { description: "Check the console for details." });
12678
12890
  }, [parseError]);
@@ -12715,7 +12927,6 @@ const Panel = ({ item, onChange, onDelete }) => {
12715
12927
  ]
12716
12928
  });
12717
12929
  };
12718
-
12719
12930
  //#endregion
12720
12931
  //#region src/components/dnd/dnd.tsx
12721
12932
  const conditionalModifiers = (args) => {
@@ -12770,7 +12981,8 @@ const Dnd$1 = ({ value: _value, props, modules = {}, onChange: _onChange, classN
12770
12981
  const prevIndex = sections.findIndex((s) => s.id === active.id);
12771
12982
  const nextIndex = sections.findIndex((s) => s.id === over.id);
12772
12983
  if (prevIndex >= 0 && nextIndex >= 0) {
12773
- const nextCode = replaceSections(value, arrayMove(sections, prevIndex, nextIndex).map((s) => s.code));
12984
+ const nextSections = arrayMove(sections, prevIndex, nextIndex);
12985
+ const nextCode = replaceSections(value, nextSections.map((s) => s.code));
12774
12986
  _onChange?.(nextCode);
12775
12987
  setCode(nextCode);
12776
12988
  }
@@ -12782,7 +12994,8 @@ const Dnd$1 = ({ value: _value, props, modules = {}, onChange: _onChange, classN
12782
12994
  name: item.name,
12783
12995
  code: item.code
12784
12996
  };
12785
- const nextCode = replaceSections(value, [...sections, newSection].map((s) => s.code));
12997
+ const nextSections = [...sections, newSection];
12998
+ const nextCode = replaceSections(value, nextSections.map((s) => s.code));
12786
12999
  _onChange?.(nextCode);
12787
13000
  setCode(nextCode);
12788
13001
  };
@@ -12818,10 +13031,11 @@ const Dnd$1 = ({ value: _value, props, modules = {}, onChange: _onChange, classN
12818
13031
  setSelectedId((prev) => prev === id ? null : id);
12819
13032
  };
12820
13033
  const onChange = (next) => {
12821
- const nextCode = replaceSections(value, sections.map((s) => s.id === next.id ? {
13034
+ const nextSections = sections.map((s) => s.id === next.id ? {
12822
13035
  ...s,
12823
13036
  ...next
12824
- } : s).map((s) => s.code));
13037
+ } : s);
13038
+ const nextCode = replaceSections(value, nextSections.map((s) => s.code));
12825
13039
  _onChange?.(nextCode);
12826
13040
  setCode(nextCode);
12827
13041
  };
@@ -12956,12 +13170,10 @@ const Dnd$1 = ({ value: _value, props, modules = {}, onChange: _onChange, classN
12956
13170
  }) })]
12957
13171
  }) });
12958
13172
  };
12959
-
12960
13173
  //#endregion
12961
13174
  //#region src/components/dnd/index.ts
12962
13175
  const Dnd = Dnd$1;
12963
13176
  Dnd.DraggableItem = DraggableItem;
12964
-
12965
13177
  //#endregion
12966
13178
  //#region src/components/editor/editor.tsx
12967
13179
  const Editor$1 = ({ defaultValue, value: _value, debounce = 1e3, onChange: _onChange, renderEditor, fragment, prettierOptions, ...props }) => {
@@ -13000,12 +13212,10 @@ const Editor$1 = ({ defaultValue, value: _value, debounce = 1e3, onChange: _onCh
13000
13212
  ...props
13001
13213
  });
13002
13214
  };
13003
-
13004
13215
  //#endregion
13005
13216
  //#region src/components/editor/index.ts
13006
13217
  const Editor = Editor$1;
13007
13218
  Editor.Core = Core;
13008
-
13009
13219
  //#endregion
13010
13220
  //#region src/components/error/error.tsx
13011
13221
  const Error$2 = ({ message, title = "An error occurred", className, onReset }) => {
@@ -13054,7 +13264,6 @@ const Error$2 = ({ message, title = "An error occurred", className, onReset }) =
13054
13264
  ]
13055
13265
  });
13056
13266
  };
13057
-
13058
13267
  //#endregion
13059
13268
  //#region src/components/error/boundary.tsx
13060
13269
  var ErrorBoundary = class extends React.Component {
@@ -13093,7 +13302,6 @@ var ErrorBoundary = class extends React.Component {
13093
13302
  return this.props.children;
13094
13303
  }
13095
13304
  };
13096
-
13097
13305
  //#endregion
13098
13306
  //#region src/components/error/guard.tsx
13099
13307
  const Guard = ({ children, onError }) => {
@@ -13144,7 +13352,6 @@ const Guard = ({ children, onError }) => {
13144
13352
  children
13145
13353
  });
13146
13354
  };
13147
-
13148
13355
  //#endregion
13149
13356
  //#region src/components/error/runtime.tsx
13150
13357
  const Runtime = ({ open = true, reset }) => {
@@ -13163,14 +13370,12 @@ const Runtime = ({ open = true, reset }) => {
13163
13370
  title: "Runtime Error"
13164
13371
  });
13165
13372
  };
13166
-
13167
13373
  //#endregion
13168
13374
  //#region src/components/error/index.ts
13169
13375
  const Error$1 = Error$2;
13170
13376
  Error$1.Boundary = ErrorBoundary;
13171
13377
  Error$1.Runtime = Runtime;
13172
13378
  Error$1.Guard = Guard;
13173
-
13174
13379
  //#endregion
13175
13380
  //#region src/components/preview/client.tsx
13176
13381
  const Client = ({ code: _code = "", className, showError, props = {}, modules = {}, frame, provider }) => {
@@ -13238,7 +13443,6 @@ const Client = ({ code: _code = "", className, showError, props = {}, modules =
13238
13443
  })
13239
13444
  }), /* @__PURE__ */ jsx(Error$1.Runtime, { open: isError })] });
13240
13445
  };
13241
-
13242
13446
  //#endregion
13243
13447
  //#region src/components/preview/preview.tsx
13244
13448
  const Preview = ({ code, props = {}, modules = {}, dynamicTailwind = false, provider, ...restProps }) => {
@@ -13310,7 +13514,6 @@ const Preview = ({ code, props = {}, modules = {}, dynamicTailwind = false, prov
13310
13514
  ...restProps
13311
13515
  });
13312
13516
  };
13313
-
13314
13517
  //#endregion
13315
13518
  //#region src/index.tsx
13316
13519
  const App = ({ children }) => {
@@ -13322,7 +13525,7 @@ App.Renderer = LiveRenderer;
13322
13525
  App.Error = Error$1;
13323
13526
  App.Editor = Editor;
13324
13527
  App.Dnd = Dnd;
13325
-
13326
13528
  //#endregion
13327
13529
  export { Dnd as LiveDnd, Editor as LiveEditor, Error$1 as LiveError, Preview as LivePreview, App as LiveProvider, App as default, LiveRenderer };
13530
+
13328
13531
  //# sourceMappingURL=index.mjs.map