@fab1o978/react-ui 0.1.3 → 0.1.5

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.cjs CHANGED
@@ -2,10 +2,24 @@
2
2
 
3
3
  var React = require('react');
4
4
  var jsxRuntime = require('react/jsx-runtime');
5
+ var react = require('@tiptap/react');
6
+ var StarterKit = require('@tiptap/starter-kit');
7
+ var Underline = require('@tiptap/extension-underline');
8
+ var Placeholder = require('@tiptap/extension-placeholder');
9
+ var transform = require('@tiptap/pm/transform');
10
+ var commands = require('@tiptap/pm/commands');
11
+ var state = require('@tiptap/pm/state');
12
+ var model = require('@tiptap/pm/model');
13
+ var schemaList = require('@tiptap/pm/schema-list');
14
+ require('@tiptap/pm/view');
15
+ require('@tiptap/pm/keymap');
5
16
 
6
17
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
18
 
8
19
  var React__default = /*#__PURE__*/_interopDefault(React);
20
+ var StarterKit__default = /*#__PURE__*/_interopDefault(StarterKit);
21
+ var Underline__default = /*#__PURE__*/_interopDefault(Underline);
22
+ var Placeholder__default = /*#__PURE__*/_interopDefault(Placeholder);
9
23
 
10
24
  // src/components/Button/Button.tsx
11
25
 
@@ -996,11 +1010,3562 @@ var ColorPicker = ({
996
1010
  );
997
1011
  };
998
1012
 
1013
+ // src/components/SlidingCounter/SlidingCounter.module.scss
1014
+ var SlidingCounter_module_default = {
1015
+ counter: "SlidingCounter_module_counter",
1016
+ sign: "SlidingCounter_module_sign",
1017
+ separator: "SlidingCounter_module_separator",
1018
+ reelWindow: "SlidingCounter_module_reelWindow",
1019
+ sm: "SlidingCounter_module_sm",
1020
+ md: "SlidingCounter_module_md",
1021
+ lg: "SlidingCounter_module_lg",
1022
+ reel: "SlidingCounter_module_reel",
1023
+ digitCell: "SlidingCounter_module_digitCell"
1024
+ };
1025
+ var COPIES = 3;
1026
+ var TOTAL = COPIES * 10;
1027
+ var DigitReel = ({ digit, direction, size }) => {
1028
+ const posRef = React.useRef(10 + digit);
1029
+ const prevDigitRef = React.useRef(digit);
1030
+ const [pos, setPos] = React.useState(10 + digit);
1031
+ const [animate, setAnimate] = React.useState(true);
1032
+ React.useEffect(() => {
1033
+ if (prevDigitRef.current === digit) return;
1034
+ const prev = prevDigitRef.current;
1035
+ let next = posRef.current;
1036
+ if (direction === "up") {
1037
+ next += digit > prev ? digit - prev : 10 - prev + digit;
1038
+ } else {
1039
+ next -= digit < prev ? prev - digit : prev + 10 - digit;
1040
+ }
1041
+ posRef.current = next;
1042
+ prevDigitRef.current = digit;
1043
+ setAnimate(true);
1044
+ setPos(next);
1045
+ }, [digit, direction]);
1046
+ const handleTransitionEnd = () => {
1047
+ const normalized = 10 + (posRef.current % 10 + 10) % 10;
1048
+ posRef.current = normalized;
1049
+ setAnimate(false);
1050
+ setPos(normalized);
1051
+ };
1052
+ const translateY = -(pos / TOTAL) * 100;
1053
+ const cells = Array.from(
1054
+ { length: COPIES },
1055
+ () => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1056
+ ).flat();
1057
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${SlidingCounter_module_default.reelWindow} ${SlidingCounter_module_default[size]}`, children: /* @__PURE__ */ jsxRuntime.jsx(
1058
+ "div",
1059
+ {
1060
+ className: SlidingCounter_module_default.reel,
1061
+ style: {
1062
+ transform: `translateY(${translateY}%)`,
1063
+ transition: animate ? void 0 : "none"
1064
+ },
1065
+ onTransitionEnd: handleTransitionEnd,
1066
+ children: cells.map((d, i) => /* @__PURE__ */ jsxRuntime.jsx("div", { className: SlidingCounter_module_default.digitCell, children: d }, i))
1067
+ }
1068
+ ) });
1069
+ };
1070
+ function splitDigits(value, minDigits, decimals) {
1071
+ const abs = Math.abs(value);
1072
+ const fixed = abs.toFixed(decimals);
1073
+ const [intPart, decPart = ""] = fixed.split(".");
1074
+ const intDigits = intPart.split("").map(Number);
1075
+ const padded = intDigits.length < minDigits ? [...Array(minDigits - intDigits.length).fill(0), ...intDigits] : intDigits;
1076
+ const decDigits = decPart.split("").map(Number);
1077
+ return { intDigits: padded, decDigits };
1078
+ }
1079
+ var SlidingCounter = ({
1080
+ value,
1081
+ minDigits = 1,
1082
+ decimals = 0,
1083
+ decimalSeparator = ".",
1084
+ size = "md",
1085
+ accent,
1086
+ className
1087
+ }) => {
1088
+ const accentVars = accent ? accentToCssVars(deriveAccent(accent), "sliding-counter") : {};
1089
+ const safeValue = isFinite(value) ? value : 0;
1090
+ const prevValueRef = React.useRef(safeValue);
1091
+ const direction = safeValue >= prevValueRef.current ? "up" : "down";
1092
+ prevValueRef.current = safeValue;
1093
+ const { intDigits, decDigits } = splitDigits(safeValue, minDigits, decimals);
1094
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1095
+ "div",
1096
+ {
1097
+ className: [SlidingCounter_module_default.counter, SlidingCounter_module_default[size], className ?? ""].filter(Boolean).join(" "),
1098
+ style: accentVars,
1099
+ "aria-label": safeValue.toFixed(decimals),
1100
+ children: [
1101
+ safeValue < 0 && /* @__PURE__ */ jsxRuntime.jsx("span", { className: SlidingCounter_module_default.sign, children: "\u2212" }),
1102
+ intDigits.map((digit, i) => /* @__PURE__ */ jsxRuntime.jsx(DigitReel, { digit, direction, size }, `int-${intDigits.length - i}`)),
1103
+ decimals > 0 && /* @__PURE__ */ jsxRuntime.jsx("span", { className: SlidingCounter_module_default.separator, children: decimalSeparator }),
1104
+ decDigits.map((digit, i) => /* @__PURE__ */ jsxRuntime.jsx(DigitReel, { digit, direction, size }, `dec-${i}`))
1105
+ ]
1106
+ }
1107
+ );
1108
+ };
1109
+
1110
+ // src/components/RichTextEditor/RichTextEditor.module.scss
1111
+ var RichTextEditor_module_default = {
1112
+ root: "RichTextEditor_module_root",
1113
+ readOnly: "RichTextEditor_module_readOnly",
1114
+ toolbar: "RichTextEditor_module_toolbar",
1115
+ toolbarGroup: "RichTextEditor_module_toolbarGroup",
1116
+ divider: "RichTextEditor_module_divider",
1117
+ toolbarButton: "RichTextEditor_module_toolbarButton",
1118
+ active: "RichTextEditor_module_active",
1119
+ headingButton: "RichTextEditor_module_headingButton",
1120
+ bubbleMenu: "RichTextEditor_module_bubbleMenu",
1121
+ editorContent: "RichTextEditor_module_editorContent"};
1122
+ var BulletListIcon = () => /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
1123
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "2.5", cy: "4", r: "1.5", fill: "currentColor" }),
1124
+ /* @__PURE__ */ jsxRuntime.jsx("line", { x1: "6", y1: "4", x2: "14", y2: "4", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }),
1125
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "2.5", cy: "8", r: "1.5", fill: "currentColor" }),
1126
+ /* @__PURE__ */ jsxRuntime.jsx("line", { x1: "6", y1: "8", x2: "14", y2: "8", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }),
1127
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "2.5", cy: "12", r: "1.5", fill: "currentColor" }),
1128
+ /* @__PURE__ */ jsxRuntime.jsx("line", { x1: "6", y1: "12", x2: "14", y2: "12", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" })
1129
+ ] });
1130
+ var OrderedListIcon = () => /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
1131
+ /* @__PURE__ */ jsxRuntime.jsx("text", { x: "0.5", y: "5.5", fontSize: "5.5", fill: "currentColor", fontFamily: "system-ui, sans-serif", children: "1." }),
1132
+ /* @__PURE__ */ jsxRuntime.jsx("line", { x1: "7", y1: "4", x2: "14", y2: "4", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }),
1133
+ /* @__PURE__ */ jsxRuntime.jsx("text", { x: "0.5", y: "9.5", fontSize: "5.5", fill: "currentColor", fontFamily: "system-ui, sans-serif", children: "2." }),
1134
+ /* @__PURE__ */ jsxRuntime.jsx("line", { x1: "7", y1: "8", x2: "14", y2: "8", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }),
1135
+ /* @__PURE__ */ jsxRuntime.jsx("text", { x: "0.5", y: "13.5", fontSize: "5.5", fill: "currentColor", fontFamily: "system-ui, sans-serif", children: "3." }),
1136
+ /* @__PURE__ */ jsxRuntime.jsx("line", { x1: "7", y1: "12", x2: "14", y2: "12", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" })
1137
+ ] });
1138
+ var Toolbar = ({ slotBefore }) => {
1139
+ const { editor } = react.useCurrentEditor();
1140
+ if (!editor) return null;
1141
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: RichTextEditor_module_default.toolbar, role: "toolbar", "aria-label": "Text formatting", children: [
1142
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: RichTextEditor_module_default.toolbarGroup, children: [
1143
+ { render: () => /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "B" }), title: "Bold", action: () => editor.chain().focus().toggleBold().run(), active: editor.isActive("bold") },
1144
+ { render: () => /* @__PURE__ */ jsxRuntime.jsx("em", { children: "I" }), title: "Italic", action: () => editor.chain().focus().toggleItalic().run(), active: editor.isActive("italic") },
1145
+ { render: () => /* @__PURE__ */ jsxRuntime.jsx("u", { children: "U" }), title: "Underline", action: () => editor.chain().focus().toggleUnderline().run(), active: editor.isActive("underline") },
1146
+ { render: () => /* @__PURE__ */ jsxRuntime.jsx("s", { children: "S" }), title: "Strikethrough", action: () => editor.chain().focus().toggleStrike().run(), active: editor.isActive("strike") }
1147
+ ].map(({ render, title, action, active }) => /* @__PURE__ */ jsxRuntime.jsx(
1148
+ "button",
1149
+ {
1150
+ type: "button",
1151
+ title,
1152
+ "aria-label": title,
1153
+ "aria-pressed": active,
1154
+ className: [RichTextEditor_module_default.toolbarButton, active ? RichTextEditor_module_default.active : ""].filter(Boolean).join(" "),
1155
+ onMouseDown: (e) => {
1156
+ e.preventDefault();
1157
+ action();
1158
+ },
1159
+ children: render()
1160
+ },
1161
+ title
1162
+ )) }),
1163
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: RichTextEditor_module_default.divider, "aria-hidden": "true" }),
1164
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: RichTextEditor_module_default.toolbarGroup, children: [1, 2, 3].map((level) => /* @__PURE__ */ jsxRuntime.jsxs(
1165
+ "button",
1166
+ {
1167
+ type: "button",
1168
+ title: `Heading ${level}`,
1169
+ "aria-label": `Heading ${level}`,
1170
+ "aria-pressed": editor.isActive("heading", { level }),
1171
+ className: [
1172
+ RichTextEditor_module_default.toolbarButton,
1173
+ RichTextEditor_module_default.headingButton,
1174
+ editor.isActive("heading", { level }) ? RichTextEditor_module_default.active : ""
1175
+ ].filter(Boolean).join(" "),
1176
+ onMouseDown: (e) => {
1177
+ e.preventDefault();
1178
+ editor.chain().focus().toggleHeading({ level }).run();
1179
+ },
1180
+ children: [
1181
+ "H",
1182
+ level
1183
+ ]
1184
+ },
1185
+ `h${level}`
1186
+ )) }),
1187
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: RichTextEditor_module_default.divider, "aria-hidden": "true" }),
1188
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: RichTextEditor_module_default.toolbarGroup, children: [
1189
+ { icon: /* @__PURE__ */ jsxRuntime.jsx(BulletListIcon, {}), title: "Bullet list", action: () => editor.chain().focus().toggleBulletList().run(), active: editor.isActive("bulletList") },
1190
+ { icon: /* @__PURE__ */ jsxRuntime.jsx(OrderedListIcon, {}), title: "Ordered list", action: () => editor.chain().focus().toggleOrderedList().run(), active: editor.isActive("orderedList") }
1191
+ ].map(({ icon, title, action, active }) => /* @__PURE__ */ jsxRuntime.jsx(
1192
+ "button",
1193
+ {
1194
+ type: "button",
1195
+ title,
1196
+ "aria-label": title,
1197
+ "aria-pressed": active,
1198
+ className: [RichTextEditor_module_default.toolbarButton, active ? RichTextEditor_module_default.active : ""].filter(Boolean).join(" "),
1199
+ onMouseDown: (e) => {
1200
+ e.preventDefault();
1201
+ action();
1202
+ },
1203
+ children: icon
1204
+ },
1205
+ title
1206
+ )) }),
1207
+ slotBefore && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1208
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: RichTextEditor_module_default.divider, "aria-hidden": "true" }),
1209
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: RichTextEditor_module_default.toolbarGroup, children: slotBefore })
1210
+ ] })
1211
+ ] });
1212
+ };
1213
+ var BubbleMenu = () => {
1214
+ const { editor } = react.useCurrentEditor();
1215
+ const menuRef = React.useRef(null);
1216
+ const [pos, setPos] = React.useState(null);
1217
+ React.useEffect(() => {
1218
+ if (!editor) return;
1219
+ const update = () => {
1220
+ const { selection } = editor.state;
1221
+ if (selection.empty) {
1222
+ setPos(null);
1223
+ return;
1224
+ }
1225
+ const { from, to } = selection;
1226
+ const start = editor.view.coordsAtPos(from);
1227
+ const end = editor.view.coordsAtPos(to);
1228
+ const halfW = (menuRef.current?.offsetWidth ?? 0) / 2;
1229
+ const menuH = menuRef.current?.offsetHeight ?? 0;
1230
+ const rawX = (start.left + end.left) / 2;
1231
+ const clampedX = Math.max(halfW + 8, Math.min(rawX, window.innerWidth - halfW - 8));
1232
+ const toolbarBottom = document.querySelector("[role='toolbar']")?.getBoundingClientRect().bottom ?? 0;
1233
+ const flip = start.top - menuH - 8 < toolbarBottom + 8;
1234
+ setPos({ x: clampedX, y: flip ? start.bottom : start.top, flip });
1235
+ };
1236
+ editor.on("selectionUpdate", update);
1237
+ editor.on("blur", () => setPos(null));
1238
+ return () => {
1239
+ editor.off("selectionUpdate", update);
1240
+ editor.off("blur", () => setPos(null));
1241
+ };
1242
+ }, [editor]);
1243
+ if (!editor) return null;
1244
+ const visible = pos !== null;
1245
+ return /* @__PURE__ */ jsxRuntime.jsx(
1246
+ "div",
1247
+ {
1248
+ ref: menuRef,
1249
+ className: RichTextEditor_module_default.bubbleMenu,
1250
+ "aria-hidden": !visible,
1251
+ style: {
1252
+ position: "fixed",
1253
+ left: pos?.x ?? 0,
1254
+ top: pos?.y ?? 0,
1255
+ transform: pos?.flip ? "translate(-50%, 8px)" : "translate(-50%, calc(-100% - 8px))",
1256
+ zIndex: 50,
1257
+ visibility: visible ? "visible" : "hidden",
1258
+ pointerEvents: visible ? "auto" : "none"
1259
+ },
1260
+ children: [
1261
+ { render: () => /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "B" }), title: "Bold", action: () => editor.chain().focus().toggleBold().run(), active: editor.isActive("bold") },
1262
+ { render: () => /* @__PURE__ */ jsxRuntime.jsx("em", { children: "I" }), title: "Italic", action: () => editor.chain().focus().toggleItalic().run(), active: editor.isActive("italic") },
1263
+ { render: () => /* @__PURE__ */ jsxRuntime.jsx("u", { children: "U" }), title: "Underline", action: () => editor.chain().focus().toggleUnderline().run(), active: editor.isActive("underline") },
1264
+ { render: () => /* @__PURE__ */ jsxRuntime.jsx("s", { children: "S" }), title: "Strikethrough", action: () => editor.chain().focus().toggleStrike().run(), active: editor.isActive("strike") }
1265
+ ].map(({ render, title, action, active }) => /* @__PURE__ */ jsxRuntime.jsx(
1266
+ "button",
1267
+ {
1268
+ type: "button",
1269
+ title,
1270
+ "aria-label": title,
1271
+ "aria-pressed": active,
1272
+ className: [RichTextEditor_module_default.toolbarButton, active ? RichTextEditor_module_default.active : ""].filter(Boolean).join(" "),
1273
+ onMouseDown: (e) => {
1274
+ e.preventDefault();
1275
+ action();
1276
+ },
1277
+ children: render()
1278
+ },
1279
+ title
1280
+ ))
1281
+ }
1282
+ );
1283
+ };
1284
+ var RichTextEditor = ({
1285
+ value,
1286
+ placeholder = "Start writing...",
1287
+ readOnly = false,
1288
+ minHeight = 200,
1289
+ maxHeight,
1290
+ accent,
1291
+ extensions = [],
1292
+ slotBefore,
1293
+ slotAfter,
1294
+ onChangeHTML,
1295
+ onChangeJSON
1296
+ }) => {
1297
+ const accentVars = accent ? accentToCssVars(deriveAccent(accent), "rich-text-editor") : {};
1298
+ const minHeightValue = typeof minHeight === "number" ? `${minHeight}px` : minHeight;
1299
+ const maxHeightValue = maxHeight !== void 0 ? typeof maxHeight === "number" ? `${maxHeight}px` : maxHeight : void 0;
1300
+ return /* @__PURE__ */ jsxRuntime.jsx(
1301
+ "div",
1302
+ {
1303
+ className: [RichTextEditor_module_default.root, readOnly ? RichTextEditor_module_default.readOnly : ""].filter(Boolean).join(" "),
1304
+ style: { ...accentVars, "--rte-min-height": minHeightValue, "--rte-max-height": maxHeightValue },
1305
+ children: /* @__PURE__ */ jsxRuntime.jsx(
1306
+ react.EditorProvider,
1307
+ {
1308
+ extensions: [
1309
+ StarterKit__default.default.configure({ heading: { levels: [1, 2, 3] } }),
1310
+ Underline__default.default,
1311
+ Placeholder__default.default.configure({ placeholder }),
1312
+ ...extensions
1313
+ ],
1314
+ content: value,
1315
+ editable: !readOnly,
1316
+ onUpdate: ({ editor }) => {
1317
+ onChangeHTML?.(editor.getHTML());
1318
+ onChangeJSON?.(editor.getJSON());
1319
+ },
1320
+ slotBefore: !readOnly ? /* @__PURE__ */ jsxRuntime.jsx(Toolbar, { slotBefore }) : void 0,
1321
+ slotAfter,
1322
+ editorContainerProps: { className: RichTextEditor_module_default.editorContent },
1323
+ children: !readOnly && /* @__PURE__ */ jsxRuntime.jsx(BubbleMenu, {})
1324
+ }
1325
+ )
1326
+ }
1327
+ );
1328
+ };
1329
+ var __defProp = Object.defineProperty;
1330
+ var __export = (target, all) => {
1331
+ for (var name in all)
1332
+ __defProp(target, name, { get: all[name], enumerable: true });
1333
+ };
1334
+ function createChainableState(config) {
1335
+ const { state, transaction } = config;
1336
+ let { selection } = transaction;
1337
+ let { doc } = transaction;
1338
+ let { storedMarks } = transaction;
1339
+ return {
1340
+ ...state,
1341
+ apply: state.apply.bind(state),
1342
+ applyTransaction: state.applyTransaction.bind(state),
1343
+ plugins: state.plugins,
1344
+ schema: state.schema,
1345
+ reconfigure: state.reconfigure.bind(state),
1346
+ toJSON: state.toJSON.bind(state),
1347
+ get storedMarks() {
1348
+ return storedMarks;
1349
+ },
1350
+ get selection() {
1351
+ return selection;
1352
+ },
1353
+ get doc() {
1354
+ return doc;
1355
+ },
1356
+ get tr() {
1357
+ selection = transaction.selection;
1358
+ doc = transaction.doc;
1359
+ storedMarks = transaction.storedMarks;
1360
+ return transaction;
1361
+ }
1362
+ };
1363
+ }
1364
+ var CommandManager = class {
1365
+ constructor(props) {
1366
+ this.editor = props.editor;
1367
+ this.rawCommands = this.editor.extensionManager.commands;
1368
+ this.customState = props.state;
1369
+ }
1370
+ get hasCustomState() {
1371
+ return !!this.customState;
1372
+ }
1373
+ get state() {
1374
+ return this.customState || this.editor.state;
1375
+ }
1376
+ get commands() {
1377
+ const { rawCommands, editor, state } = this;
1378
+ const { view } = editor;
1379
+ const { tr } = state;
1380
+ const props = this.buildProps(tr);
1381
+ return Object.fromEntries(
1382
+ Object.entries(rawCommands).map(([name, command2]) => {
1383
+ const method = (...args) => {
1384
+ const callback = command2(...args)(props);
1385
+ if (!tr.getMeta("preventDispatch") && !this.hasCustomState) {
1386
+ view.dispatch(tr);
1387
+ }
1388
+ return callback;
1389
+ };
1390
+ return [name, method];
1391
+ })
1392
+ );
1393
+ }
1394
+ get chain() {
1395
+ return () => this.createChain();
1396
+ }
1397
+ get can() {
1398
+ return () => this.createCan();
1399
+ }
1400
+ createChain(startTr, shouldDispatch = true) {
1401
+ const { rawCommands, editor, state } = this;
1402
+ const { view } = editor;
1403
+ const callbacks = [];
1404
+ const hasStartTransaction = !!startTr;
1405
+ const tr = startTr || state.tr;
1406
+ const run3 = () => {
1407
+ if (!hasStartTransaction && shouldDispatch && !tr.getMeta("preventDispatch") && !this.hasCustomState) {
1408
+ view.dispatch(tr);
1409
+ }
1410
+ return callbacks.every((callback) => callback === true);
1411
+ };
1412
+ const chain = {
1413
+ ...Object.fromEntries(
1414
+ Object.entries(rawCommands).map(([name, command2]) => {
1415
+ const chainedCommand = (...args) => {
1416
+ const props = this.buildProps(tr, shouldDispatch);
1417
+ const callback = command2(...args)(props);
1418
+ callbacks.push(callback);
1419
+ return chain;
1420
+ };
1421
+ return [name, chainedCommand];
1422
+ })
1423
+ ),
1424
+ run: run3
1425
+ };
1426
+ return chain;
1427
+ }
1428
+ createCan(startTr) {
1429
+ const { rawCommands, state } = this;
1430
+ const dispatch = false;
1431
+ const tr = startTr || state.tr;
1432
+ const props = this.buildProps(tr, dispatch);
1433
+ const formattedCommands = Object.fromEntries(
1434
+ Object.entries(rawCommands).map(([name, command2]) => {
1435
+ return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })];
1436
+ })
1437
+ );
1438
+ return {
1439
+ ...formattedCommands,
1440
+ chain: () => this.createChain(tr, dispatch)
1441
+ };
1442
+ }
1443
+ buildProps(tr, shouldDispatch = true) {
1444
+ const { rawCommands, editor, state } = this;
1445
+ const { view } = editor;
1446
+ const props = {
1447
+ tr,
1448
+ editor,
1449
+ view,
1450
+ state: createChainableState({
1451
+ state,
1452
+ transaction: tr
1453
+ }),
1454
+ dispatch: shouldDispatch ? () => void 0 : void 0,
1455
+ chain: () => this.createChain(tr, shouldDispatch),
1456
+ can: () => this.createCan(tr),
1457
+ get commands() {
1458
+ return Object.fromEntries(
1459
+ Object.entries(rawCommands).map(([name, command2]) => {
1460
+ return [name, (...args) => command2(...args)(props)];
1461
+ })
1462
+ );
1463
+ }
1464
+ };
1465
+ return props;
1466
+ }
1467
+ };
1468
+ var commands_exports = {};
1469
+ __export(commands_exports, {
1470
+ blur: () => blur,
1471
+ clearContent: () => clearContent,
1472
+ clearNodes: () => clearNodes,
1473
+ command: () => command,
1474
+ createParagraphNear: () => createParagraphNear,
1475
+ cut: () => cut,
1476
+ deleteCurrentNode: () => deleteCurrentNode,
1477
+ deleteNode: () => deleteNode,
1478
+ deleteRange: () => deleteRange,
1479
+ deleteSelection: () => deleteSelection,
1480
+ enter: () => enter,
1481
+ exitCode: () => exitCode,
1482
+ extendMarkRange: () => extendMarkRange,
1483
+ first: () => first,
1484
+ focus: () => focus,
1485
+ forEach: () => forEach,
1486
+ insertContent: () => insertContent,
1487
+ insertContentAt: () => insertContentAt,
1488
+ joinBackward: () => joinBackward,
1489
+ joinDown: () => joinDown,
1490
+ joinForward: () => joinForward,
1491
+ joinItemBackward: () => joinItemBackward,
1492
+ joinItemForward: () => joinItemForward,
1493
+ joinTextblockBackward: () => joinTextblockBackward,
1494
+ joinTextblockForward: () => joinTextblockForward,
1495
+ joinUp: () => joinUp,
1496
+ keyboardShortcut: () => keyboardShortcut,
1497
+ lift: () => lift,
1498
+ liftEmptyBlock: () => liftEmptyBlock,
1499
+ liftListItem: () => liftListItem,
1500
+ newlineInCode: () => newlineInCode,
1501
+ resetAttributes: () => resetAttributes,
1502
+ scrollIntoView: () => scrollIntoView,
1503
+ selectAll: () => selectAll,
1504
+ selectNodeBackward: () => selectNodeBackward,
1505
+ selectNodeForward: () => selectNodeForward,
1506
+ selectParentNode: () => selectParentNode,
1507
+ selectTextblockEnd: () => selectTextblockEnd,
1508
+ selectTextblockStart: () => selectTextblockStart,
1509
+ setContent: () => setContent,
1510
+ setMark: () => setMark,
1511
+ setMeta: () => setMeta,
1512
+ setNode: () => setNode,
1513
+ setNodeSelection: () => setNodeSelection,
1514
+ setTextDirection: () => setTextDirection,
1515
+ setTextSelection: () => setTextSelection,
1516
+ sinkListItem: () => sinkListItem,
1517
+ splitBlock: () => splitBlock,
1518
+ splitListItem: () => splitListItem,
1519
+ toggleList: () => toggleList,
1520
+ toggleMark: () => toggleMark,
1521
+ toggleNode: () => toggleNode,
1522
+ toggleWrap: () => toggleWrap,
1523
+ undoInputRule: () => undoInputRule,
1524
+ unsetAllMarks: () => unsetAllMarks,
1525
+ unsetMark: () => unsetMark,
1526
+ unsetTextDirection: () => unsetTextDirection,
1527
+ updateAttributes: () => updateAttributes,
1528
+ wrapIn: () => wrapIn,
1529
+ wrapInList: () => wrapInList
1530
+ });
1531
+ var blur = () => ({ editor, view }) => {
1532
+ requestAnimationFrame(() => {
1533
+ var _a;
1534
+ if (!editor.isDestroyed) {
1535
+ view.dom.blur();
1536
+ (_a = window == null ? void 0 : window.getSelection()) == null ? void 0 : _a.removeAllRanges();
1537
+ }
1538
+ });
1539
+ return true;
1540
+ };
1541
+ var clearContent = (emitUpdate = true) => ({ commands }) => {
1542
+ return commands.setContent("", { emitUpdate });
1543
+ };
1544
+ var clearNodes = () => ({ state, tr, dispatch }) => {
1545
+ const { selection } = tr;
1546
+ const { ranges } = selection;
1547
+ if (!dispatch) {
1548
+ return true;
1549
+ }
1550
+ ranges.forEach(({ $from, $to }) => {
1551
+ state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
1552
+ if (node.type.isText) {
1553
+ return;
1554
+ }
1555
+ const { doc, mapping } = tr;
1556
+ const $mappedFrom = doc.resolve(mapping.map(pos));
1557
+ const $mappedTo = doc.resolve(mapping.map(pos + node.nodeSize));
1558
+ const nodeRange = $mappedFrom.blockRange($mappedTo);
1559
+ if (!nodeRange) {
1560
+ return;
1561
+ }
1562
+ const targetLiftDepth = transform.liftTarget(nodeRange);
1563
+ if (node.type.isTextblock) {
1564
+ const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index());
1565
+ tr.setNodeMarkup(nodeRange.start, defaultType);
1566
+ }
1567
+ if (targetLiftDepth || targetLiftDepth === 0) {
1568
+ tr.lift(nodeRange, targetLiftDepth);
1569
+ }
1570
+ });
1571
+ });
1572
+ return true;
1573
+ };
1574
+ var command = (fn) => (props) => {
1575
+ return fn(props);
1576
+ };
1577
+ var createParagraphNear = () => ({ state, dispatch }) => {
1578
+ return commands.createParagraphNear(state, dispatch);
1579
+ };
1580
+ var cut = (originRange, targetPos) => ({ editor, tr }) => {
1581
+ const { state: state$1 } = editor;
1582
+ const contentSlice = state$1.doc.slice(originRange.from, originRange.to);
1583
+ tr.deleteRange(originRange.from, originRange.to);
1584
+ const newPos = tr.mapping.map(targetPos);
1585
+ tr.insert(newPos, contentSlice.content);
1586
+ tr.setSelection(new state.TextSelection(tr.doc.resolve(Math.max(newPos - 1, 0))));
1587
+ return true;
1588
+ };
1589
+ var deleteCurrentNode = () => ({ tr, dispatch }) => {
1590
+ const { selection } = tr;
1591
+ const currentNode = selection.$anchor.node();
1592
+ if (currentNode.content.size > 0) {
1593
+ return false;
1594
+ }
1595
+ const $pos = tr.selection.$anchor;
1596
+ for (let depth = $pos.depth; depth > 0; depth -= 1) {
1597
+ const node = $pos.node(depth);
1598
+ if (node.type === currentNode.type) {
1599
+ if (dispatch) {
1600
+ const from = $pos.before(depth);
1601
+ const to = $pos.after(depth);
1602
+ tr.delete(from, to).scrollIntoView();
1603
+ }
1604
+ return true;
1605
+ }
1606
+ }
1607
+ return false;
1608
+ };
1609
+ function getNodeType(nameOrType, schema) {
1610
+ if (typeof nameOrType === "string") {
1611
+ if (!schema.nodes[nameOrType]) {
1612
+ throw Error(
1613
+ `There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`
1614
+ );
1615
+ }
1616
+ return schema.nodes[nameOrType];
1617
+ }
1618
+ return nameOrType;
1619
+ }
1620
+ var deleteNode = (typeOrName) => ({ tr, state, dispatch }) => {
1621
+ const type = getNodeType(typeOrName, state.schema);
1622
+ const $pos = tr.selection.$anchor;
1623
+ for (let depth = $pos.depth; depth > 0; depth -= 1) {
1624
+ const node = $pos.node(depth);
1625
+ if (node.type === type) {
1626
+ if (dispatch) {
1627
+ const from = $pos.before(depth);
1628
+ const to = $pos.after(depth);
1629
+ tr.delete(from, to).scrollIntoView();
1630
+ }
1631
+ return true;
1632
+ }
1633
+ }
1634
+ return false;
1635
+ };
1636
+ var deleteRange = (range) => ({ tr, dispatch }) => {
1637
+ const { from, to } = range;
1638
+ if (dispatch) {
1639
+ tr.delete(from, to);
1640
+ }
1641
+ return true;
1642
+ };
1643
+ var hasTextContent = (nodeSpec) => {
1644
+ if (!nodeSpec.content) {
1645
+ return false;
1646
+ }
1647
+ const textRegex = /^text(\*|\+)/;
1648
+ return textRegex.test(nodeSpec.content);
1649
+ };
1650
+ var expandSelectionForSide = ($pos, schema, side) => {
1651
+ if (!$pos.parent.isInline) {
1652
+ return $pos.pos;
1653
+ }
1654
+ if (side === "left" && $pos.pos > $pos.start() || side === "right" && $pos.pos < $pos.end()) {
1655
+ return $pos.pos;
1656
+ }
1657
+ const parentContent = schema.nodes[$pos.parent.type.name].spec;
1658
+ if (!hasTextContent(parentContent)) {
1659
+ return $pos.pos;
1660
+ }
1661
+ return side === "left" ? $pos.start() - 1 : $pos.end() + 1;
1662
+ };
1663
+ var expandSelectionForInlineText = ($from, $to, schema) => {
1664
+ const from = expandSelectionForSide($from, schema, "left");
1665
+ const to = expandSelectionForSide($to, schema, "right");
1666
+ return { from, to };
1667
+ };
1668
+ var deleteSelection = () => ({ state, dispatch }) => {
1669
+ const { $from, $to } = state.selection;
1670
+ if (state.selection.empty) {
1671
+ return false;
1672
+ }
1673
+ const { from, to } = expandSelectionForInlineText($from, $to, state.schema);
1674
+ if (dispatch) {
1675
+ state.tr.deleteRange(from, to).scrollIntoView();
1676
+ dispatch(state.tr);
1677
+ }
1678
+ return true;
1679
+ };
1680
+ var enter = () => ({ commands }) => {
1681
+ return commands.keyboardShortcut("Enter");
1682
+ };
1683
+ var exitCode = () => ({ state, dispatch }) => {
1684
+ return commands.exitCode(state, dispatch);
1685
+ };
1686
+ function isRegExp(value) {
1687
+ return Object.prototype.toString.call(value) === "[object RegExp]";
1688
+ }
1689
+ function objectIncludes(object1, object2, options = { strict: true }) {
1690
+ const keys = Object.keys(object2);
1691
+ if (!keys.length) {
1692
+ return true;
1693
+ }
1694
+ return keys.every((key) => {
1695
+ if (options.strict) {
1696
+ return object2[key] === object1[key];
1697
+ }
1698
+ if (isRegExp(object2[key])) {
1699
+ return object2[key].test(object1[key]);
1700
+ }
1701
+ return object2[key] === object1[key];
1702
+ });
1703
+ }
1704
+ function findMarkInSet(marks, type, attributes = {}) {
1705
+ return marks.find((item) => {
1706
+ return item.type === type && objectIncludes(
1707
+ // Only check equality for the attributes that are provided
1708
+ Object.fromEntries(Object.keys(attributes).map((k) => [k, item.attrs[k]])),
1709
+ attributes
1710
+ );
1711
+ });
1712
+ }
1713
+ function isMarkInSet(marks, type, attributes = {}) {
1714
+ return !!findMarkInSet(marks, type, attributes);
1715
+ }
1716
+ function getMarkRange($pos, type, attributes) {
1717
+ if (!$pos || !type) {
1718
+ return;
1719
+ }
1720
+ let start = $pos.parent.childAfter($pos.parentOffset);
1721
+ if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) {
1722
+ start = $pos.parent.childBefore($pos.parentOffset);
1723
+ }
1724
+ if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) {
1725
+ return;
1726
+ }
1727
+ if (!attributes) {
1728
+ const firstMark = start.node.marks.find((mark2) => mark2.type === type);
1729
+ if (firstMark) {
1730
+ attributes = firstMark.attrs;
1731
+ }
1732
+ }
1733
+ const mark = findMarkInSet([...start.node.marks], type, attributes);
1734
+ if (!mark) {
1735
+ return;
1736
+ }
1737
+ let startIndex = start.index;
1738
+ let startPos = $pos.start() + start.offset;
1739
+ let endIndex = startIndex + 1;
1740
+ let endPos = startPos + start.node.nodeSize;
1741
+ while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) {
1742
+ startIndex -= 1;
1743
+ startPos -= $pos.parent.child(startIndex).nodeSize;
1744
+ }
1745
+ while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) {
1746
+ endPos += $pos.parent.child(endIndex).nodeSize;
1747
+ endIndex += 1;
1748
+ }
1749
+ return {
1750
+ from: startPos,
1751
+ to: endPos
1752
+ };
1753
+ }
1754
+ function getMarkType(nameOrType, schema) {
1755
+ if (typeof nameOrType === "string") {
1756
+ if (!schema.marks[nameOrType]) {
1757
+ throw Error(
1758
+ `There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`
1759
+ );
1760
+ }
1761
+ return schema.marks[nameOrType];
1762
+ }
1763
+ return nameOrType;
1764
+ }
1765
+ var extendMarkRange = (typeOrName, attributes) => ({ tr, state: state$1, dispatch }) => {
1766
+ const type = getMarkType(typeOrName, state$1.schema);
1767
+ const { doc, selection } = tr;
1768
+ const { $from, from, to } = selection;
1769
+ if (dispatch) {
1770
+ const range = getMarkRange($from, type, attributes);
1771
+ if (range && range.from <= from && range.to >= to) {
1772
+ const newSelection = state.TextSelection.create(doc, range.from, range.to);
1773
+ tr.setSelection(newSelection);
1774
+ }
1775
+ }
1776
+ return true;
1777
+ };
1778
+ var first = (commands) => (props) => {
1779
+ const items = typeof commands === "function" ? commands(props) : commands;
1780
+ for (let i = 0; i < items.length; i += 1) {
1781
+ if (items[i](props)) {
1782
+ return true;
1783
+ }
1784
+ }
1785
+ return false;
1786
+ };
1787
+ function isTextSelection(value) {
1788
+ return value instanceof state.TextSelection;
1789
+ }
1790
+ function minMax(value = 0, min = 0, max = 0) {
1791
+ return Math.min(Math.max(value, min), max);
1792
+ }
1793
+ function resolveFocusPosition(doc, position = null) {
1794
+ if (!position) {
1795
+ return null;
1796
+ }
1797
+ const selectionAtStart = state.Selection.atStart(doc);
1798
+ const selectionAtEnd = state.Selection.atEnd(doc);
1799
+ if (position === "start" || position === true) {
1800
+ return selectionAtStart;
1801
+ }
1802
+ if (position === "end") {
1803
+ return selectionAtEnd;
1804
+ }
1805
+ const minPos = selectionAtStart.from;
1806
+ const maxPos = selectionAtEnd.to;
1807
+ if (position === "all") {
1808
+ return state.TextSelection.create(
1809
+ doc,
1810
+ minMax(0, minPos, maxPos),
1811
+ minMax(doc.content.size, minPos, maxPos)
1812
+ );
1813
+ }
1814
+ return state.TextSelection.create(
1815
+ doc,
1816
+ minMax(position, minPos, maxPos),
1817
+ minMax(position, minPos, maxPos)
1818
+ );
1819
+ }
1820
+ function isAndroid() {
1821
+ return navigator.platform === "Android" || /android/i.test(navigator.userAgent);
1822
+ }
1823
+ function isiOS() {
1824
+ return ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"].includes(
1825
+ navigator.platform
1826
+ ) || // iPad on iOS 13 detection
1827
+ navigator.userAgent.includes("Mac") && "ontouchend" in document;
1828
+ }
1829
+ function isSafari() {
1830
+ return typeof navigator !== "undefined" ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false;
1831
+ }
1832
+ var focus = (position = null, options = {}) => ({ editor, view, tr, dispatch }) => {
1833
+ options = {
1834
+ scrollIntoView: true,
1835
+ ...options
1836
+ };
1837
+ const delayedFocus = () => {
1838
+ if (isiOS() || isAndroid()) {
1839
+ view.dom.focus();
1840
+ }
1841
+ if (isSafari() && !isiOS() && !isAndroid()) {
1842
+ view.dom.focus({ preventScroll: true });
1843
+ }
1844
+ requestAnimationFrame(() => {
1845
+ if (!editor.isDestroyed) {
1846
+ view.focus();
1847
+ if (options == null ? void 0 : options.scrollIntoView) {
1848
+ editor.commands.scrollIntoView();
1849
+ }
1850
+ }
1851
+ });
1852
+ };
1853
+ try {
1854
+ if (view.hasFocus() && position === null || position === false) {
1855
+ return true;
1856
+ }
1857
+ } catch {
1858
+ return false;
1859
+ }
1860
+ if (dispatch && position === null && !isTextSelection(editor.state.selection)) {
1861
+ delayedFocus();
1862
+ return true;
1863
+ }
1864
+ const selection = resolveFocusPosition(tr.doc, position) || editor.state.selection;
1865
+ const isSameSelection = editor.state.selection.eq(selection);
1866
+ if (dispatch) {
1867
+ if (!isSameSelection) {
1868
+ tr.setSelection(selection);
1869
+ }
1870
+ if (isSameSelection && tr.storedMarks) {
1871
+ tr.setStoredMarks(tr.storedMarks);
1872
+ }
1873
+ delayedFocus();
1874
+ }
1875
+ return true;
1876
+ };
1877
+ var forEach = (items, fn) => (props) => {
1878
+ return items.every((item, index) => fn(item, { ...props, index }));
1879
+ };
1880
+ var insertContent = (value, options) => ({ tr, commands }) => {
1881
+ return commands.insertContentAt(
1882
+ { from: tr.selection.from, to: tr.selection.to },
1883
+ value,
1884
+ options
1885
+ );
1886
+ };
1887
+ var removeWhitespaces = (node) => {
1888
+ const children = node.childNodes;
1889
+ for (let i = children.length - 1; i >= 0; i -= 1) {
1890
+ const child = children[i];
1891
+ if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) {
1892
+ node.removeChild(child);
1893
+ } else if (child.nodeType === 1) {
1894
+ removeWhitespaces(child);
1895
+ }
1896
+ }
1897
+ return node;
1898
+ };
1899
+ function elementFromString(value) {
1900
+ if (typeof window === "undefined") {
1901
+ throw new Error(
1902
+ "[tiptap error]: there is no window object available, so this function cannot be used"
1903
+ );
1904
+ }
1905
+ const wrappedValue = `<body>${value}</body>`;
1906
+ const html = new window.DOMParser().parseFromString(wrappedValue, "text/html").body;
1907
+ return removeWhitespaces(html);
1908
+ }
1909
+ function createNodeFromContent(content, schema, options) {
1910
+ if (content instanceof model.Node || content instanceof model.Fragment) {
1911
+ return content;
1912
+ }
1913
+ options = {
1914
+ slice: true,
1915
+ parseOptions: {},
1916
+ ...options
1917
+ };
1918
+ const isJSONContent = typeof content === "object" && content !== null;
1919
+ const isTextContent = typeof content === "string";
1920
+ if (isJSONContent) {
1921
+ try {
1922
+ const isArrayContent = Array.isArray(content) && content.length > 0;
1923
+ if (isArrayContent) {
1924
+ return model.Fragment.fromArray(content.map((item) => schema.nodeFromJSON(item)));
1925
+ }
1926
+ const node = schema.nodeFromJSON(content);
1927
+ if (options.errorOnInvalidContent) {
1928
+ node.check();
1929
+ }
1930
+ return node;
1931
+ } catch (error) {
1932
+ if (options.errorOnInvalidContent) {
1933
+ throw new Error("[tiptap error]: Invalid JSON content", { cause: error });
1934
+ }
1935
+ console.warn("[tiptap warn]: Invalid content.", "Passed value:", content, "Error:", error);
1936
+ return createNodeFromContent("", schema, options);
1937
+ }
1938
+ }
1939
+ if (isTextContent) {
1940
+ if (options.errorOnInvalidContent) {
1941
+ let hasInvalidContent = false;
1942
+ let invalidContent = "";
1943
+ const contentCheckSchema = new model.Schema({
1944
+ topNode: schema.spec.topNode,
1945
+ marks: schema.spec.marks,
1946
+ // Prosemirror's schemas are executed such that: the last to execute, matches last
1947
+ // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle
1948
+ nodes: schema.spec.nodes.append({
1949
+ __tiptap__private__unknown__catch__all__node: {
1950
+ content: "inline*",
1951
+ group: "block",
1952
+ parseDOM: [
1953
+ {
1954
+ tag: "*",
1955
+ getAttrs: (e) => {
1956
+ hasInvalidContent = true;
1957
+ invalidContent = typeof e === "string" ? e : e.outerHTML;
1958
+ return null;
1959
+ }
1960
+ }
1961
+ ]
1962
+ }
1963
+ })
1964
+ });
1965
+ if (options.slice) {
1966
+ model.DOMParser.fromSchema(contentCheckSchema).parseSlice(
1967
+ elementFromString(content),
1968
+ options.parseOptions
1969
+ );
1970
+ } else {
1971
+ model.DOMParser.fromSchema(contentCheckSchema).parse(
1972
+ elementFromString(content),
1973
+ options.parseOptions
1974
+ );
1975
+ }
1976
+ if (options.errorOnInvalidContent && hasInvalidContent) {
1977
+ throw new Error("[tiptap error]: Invalid HTML content", {
1978
+ cause: new Error(`Invalid element found: ${invalidContent}`)
1979
+ });
1980
+ }
1981
+ }
1982
+ const parser = model.DOMParser.fromSchema(schema);
1983
+ if (options.slice) {
1984
+ return parser.parseSlice(elementFromString(content), options.parseOptions).content;
1985
+ }
1986
+ return parser.parse(elementFromString(content), options.parseOptions);
1987
+ }
1988
+ return createNodeFromContent("", schema, options);
1989
+ }
1990
+ function selectionToInsertionEnd(tr, startLen, bias) {
1991
+ const last = tr.steps.length - 1;
1992
+ if (last < startLen) {
1993
+ return;
1994
+ }
1995
+ const step = tr.steps[last];
1996
+ if (!(step instanceof transform.ReplaceStep || step instanceof transform.ReplaceAroundStep)) {
1997
+ return;
1998
+ }
1999
+ const map = tr.mapping.maps[last];
2000
+ let end = 0;
2001
+ map.forEach((_from, _to, _newFrom, newTo) => {
2002
+ if (end === 0) {
2003
+ end = newTo;
2004
+ }
2005
+ });
2006
+ tr.setSelection(state.Selection.near(tr.doc.resolve(end), bias));
2007
+ }
2008
+ var isFragment = (nodeOrFragment) => {
2009
+ return !("type" in nodeOrFragment);
2010
+ };
2011
+ var insertContentAt = (position, value, options) => ({ tr, dispatch, editor }) => {
2012
+ var _a;
2013
+ if (dispatch) {
2014
+ options = {
2015
+ parseOptions: editor.options.parseOptions,
2016
+ updateSelection: true,
2017
+ applyInputRules: false,
2018
+ applyPasteRules: false,
2019
+ ...options
2020
+ };
2021
+ let content;
2022
+ const emitContentError = (error) => {
2023
+ editor.emit("contentError", {
2024
+ editor,
2025
+ error,
2026
+ disableCollaboration: () => {
2027
+ if ("collaboration" in editor.storage && typeof editor.storage.collaboration === "object" && editor.storage.collaboration) {
2028
+ editor.storage.collaboration.isDisabled = true;
2029
+ }
2030
+ }
2031
+ });
2032
+ };
2033
+ const parseOptions = {
2034
+ preserveWhitespace: "full",
2035
+ ...options.parseOptions
2036
+ };
2037
+ if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) {
2038
+ try {
2039
+ createNodeFromContent(value, editor.schema, {
2040
+ parseOptions,
2041
+ errorOnInvalidContent: true
2042
+ });
2043
+ } catch (e) {
2044
+ emitContentError(e);
2045
+ }
2046
+ }
2047
+ try {
2048
+ content = createNodeFromContent(value, editor.schema, {
2049
+ parseOptions,
2050
+ errorOnInvalidContent: (_a = options.errorOnInvalidContent) != null ? _a : editor.options.enableContentCheck
2051
+ });
2052
+ } catch (e) {
2053
+ emitContentError(e);
2054
+ return false;
2055
+ }
2056
+ let { from, to } = typeof position === "number" ? { from: position, to: position } : { from: position.from, to: position.to };
2057
+ let isOnlyTextContent = true;
2058
+ let isOnlyBlockContent = true;
2059
+ const nodes = isFragment(content) ? content : [content];
2060
+ nodes.forEach((node) => {
2061
+ node.check();
2062
+ isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false;
2063
+ isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false;
2064
+ });
2065
+ if (from === to && isOnlyBlockContent) {
2066
+ const { parent } = tr.doc.resolve(from);
2067
+ const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount;
2068
+ if (isEmptyTextBlock) {
2069
+ from -= 1;
2070
+ to += 1;
2071
+ }
2072
+ }
2073
+ let newContent;
2074
+ if (isOnlyTextContent) {
2075
+ if (Array.isArray(value)) {
2076
+ newContent = value.map((v) => v.text || "").join("");
2077
+ } else if (value instanceof model.Fragment) {
2078
+ let text = "";
2079
+ value.forEach((node) => {
2080
+ if (node.text) {
2081
+ text += node.text;
2082
+ }
2083
+ });
2084
+ newContent = text;
2085
+ } else if (typeof value === "object" && !!value && !!value.text) {
2086
+ newContent = value.text;
2087
+ } else {
2088
+ newContent = value;
2089
+ }
2090
+ tr.insertText(newContent, from, to);
2091
+ } else {
2092
+ newContent = content;
2093
+ const $from = tr.doc.resolve(from);
2094
+ const $fromNode = $from.node();
2095
+ const fromSelectionAtStart = $from.parentOffset === 0;
2096
+ const isTextSelection2 = $fromNode.isText || $fromNode.isTextblock;
2097
+ const hasContent = $fromNode.content.size > 0;
2098
+ if (fromSelectionAtStart && isTextSelection2 && hasContent && isOnlyBlockContent) {
2099
+ from = Math.max(0, from - 1);
2100
+ }
2101
+ tr.replaceWith(from, to, newContent);
2102
+ }
2103
+ if (options.updateSelection) {
2104
+ selectionToInsertionEnd(tr, tr.steps.length - 1, -1);
2105
+ }
2106
+ if (options.applyInputRules) {
2107
+ tr.setMeta("applyInputRules", { from, text: newContent });
2108
+ }
2109
+ if (options.applyPasteRules) {
2110
+ tr.setMeta("applyPasteRules", { from, text: newContent });
2111
+ }
2112
+ }
2113
+ return true;
2114
+ };
2115
+ var joinUp = () => ({ state, dispatch }) => {
2116
+ return commands.joinUp(state, dispatch);
2117
+ };
2118
+ var joinDown = () => ({ state, dispatch }) => {
2119
+ return commands.joinDown(state, dispatch);
2120
+ };
2121
+ var joinBackward = () => ({ state, dispatch }) => {
2122
+ return commands.joinBackward(state, dispatch);
2123
+ };
2124
+ var joinForward = () => ({ state, dispatch }) => {
2125
+ return commands.joinForward(state, dispatch);
2126
+ };
2127
+ var joinItemBackward = () => ({ state, dispatch, tr }) => {
2128
+ try {
2129
+ const point = transform.joinPoint(state.doc, state.selection.$from.pos, -1);
2130
+ if (point === null || point === void 0) {
2131
+ return false;
2132
+ }
2133
+ tr.join(point, 2);
2134
+ if (dispatch) {
2135
+ dispatch(tr);
2136
+ }
2137
+ return true;
2138
+ } catch {
2139
+ return false;
2140
+ }
2141
+ };
2142
+ var joinItemForward = () => ({ state, dispatch, tr }) => {
2143
+ try {
2144
+ const point = transform.joinPoint(state.doc, state.selection.$from.pos, 1);
2145
+ if (point === null || point === void 0) {
2146
+ return false;
2147
+ }
2148
+ tr.join(point, 2);
2149
+ if (dispatch) {
2150
+ dispatch(tr);
2151
+ }
2152
+ return true;
2153
+ } catch {
2154
+ return false;
2155
+ }
2156
+ };
2157
+ var joinTextblockBackward = () => ({ state, dispatch }) => {
2158
+ return commands.joinTextblockBackward(state, dispatch);
2159
+ };
2160
+ var joinTextblockForward = () => ({ state, dispatch }) => {
2161
+ return commands.joinTextblockForward(state, dispatch);
2162
+ };
2163
+ function isMacOS() {
2164
+ return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
2165
+ }
2166
+ function normalizeKeyName(name) {
2167
+ const parts = name.split(/-(?!$)/);
2168
+ let result = parts[parts.length - 1];
2169
+ if (result === "Space") {
2170
+ result = " ";
2171
+ }
2172
+ let alt;
2173
+ let ctrl;
2174
+ let shift;
2175
+ let meta;
2176
+ for (let i = 0; i < parts.length - 1; i += 1) {
2177
+ const mod = parts[i];
2178
+ if (/^(cmd|meta|m)$/i.test(mod)) {
2179
+ meta = true;
2180
+ } else if (/^a(lt)?$/i.test(mod)) {
2181
+ alt = true;
2182
+ } else if (/^(c|ctrl|control)$/i.test(mod)) {
2183
+ ctrl = true;
2184
+ } else if (/^s(hift)?$/i.test(mod)) {
2185
+ shift = true;
2186
+ } else if (/^mod$/i.test(mod)) {
2187
+ if (isiOS() || isMacOS()) {
2188
+ meta = true;
2189
+ } else {
2190
+ ctrl = true;
2191
+ }
2192
+ } else {
2193
+ throw new Error(`Unrecognized modifier name: ${mod}`);
2194
+ }
2195
+ }
2196
+ if (alt) {
2197
+ result = `Alt-${result}`;
2198
+ }
2199
+ if (ctrl) {
2200
+ result = `Ctrl-${result}`;
2201
+ }
2202
+ if (meta) {
2203
+ result = `Meta-${result}`;
2204
+ }
2205
+ if (shift) {
2206
+ result = `Shift-${result}`;
2207
+ }
2208
+ return result;
2209
+ }
2210
+ var keyboardShortcut = (name) => ({ editor, view, tr, dispatch }) => {
2211
+ const keys = normalizeKeyName(name).split(/-(?!$)/);
2212
+ const key = keys.find((item) => !["Alt", "Ctrl", "Meta", "Shift"].includes(item));
2213
+ const event = new KeyboardEvent("keydown", {
2214
+ key: key === "Space" ? " " : key,
2215
+ altKey: keys.includes("Alt"),
2216
+ ctrlKey: keys.includes("Ctrl"),
2217
+ metaKey: keys.includes("Meta"),
2218
+ shiftKey: keys.includes("Shift"),
2219
+ bubbles: true,
2220
+ cancelable: true
2221
+ });
2222
+ const capturedTransaction = editor.captureTransaction(() => {
2223
+ view.someProp("handleKeyDown", (f) => f(view, event));
2224
+ });
2225
+ capturedTransaction == null ? void 0 : capturedTransaction.steps.forEach((step) => {
2226
+ const newStep = step.map(tr.mapping);
2227
+ if (newStep && dispatch) {
2228
+ tr.maybeStep(newStep);
2229
+ }
2230
+ });
2231
+ return true;
2232
+ };
2233
+ function isNodeActive(state, typeOrName, attributes = {}) {
2234
+ const { from, to, empty } = state.selection;
2235
+ const type = typeOrName ? getNodeType(typeOrName, state.schema) : null;
2236
+ const nodeRanges = [];
2237
+ state.doc.nodesBetween(from, to, (node, pos) => {
2238
+ if (node.isText) {
2239
+ return;
2240
+ }
2241
+ const relativeFrom = Math.max(from, pos);
2242
+ const relativeTo = Math.min(to, pos + node.nodeSize);
2243
+ nodeRanges.push({
2244
+ node,
2245
+ from: relativeFrom,
2246
+ to: relativeTo
2247
+ });
2248
+ });
2249
+ const selectionRange = to - from;
2250
+ const matchedNodeRanges = nodeRanges.filter((nodeRange) => {
2251
+ if (!type) {
2252
+ return true;
2253
+ }
2254
+ return type.name === nodeRange.node.type.name;
2255
+ }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }));
2256
+ if (empty) {
2257
+ return !!matchedNodeRanges.length;
2258
+ }
2259
+ const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0);
2260
+ return range >= selectionRange;
2261
+ }
2262
+ var lift = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
2263
+ const type = getNodeType(typeOrName, state.schema);
2264
+ const isActive2 = isNodeActive(state, type, attributes);
2265
+ if (!isActive2) {
2266
+ return false;
2267
+ }
2268
+ return commands.lift(state, dispatch);
2269
+ };
2270
+ var liftEmptyBlock = () => ({ state, dispatch }) => {
2271
+ return commands.liftEmptyBlock(state, dispatch);
2272
+ };
2273
+ var liftListItem = (typeOrName) => ({ state, dispatch }) => {
2274
+ const type = getNodeType(typeOrName, state.schema);
2275
+ return schemaList.liftListItem(type)(state, dispatch);
2276
+ };
2277
+ var newlineInCode = () => ({ state, dispatch }) => {
2278
+ return commands.newlineInCode(state, dispatch);
2279
+ };
2280
+ function getSchemaTypeNameByName(name, schema) {
2281
+ if (schema.nodes[name]) {
2282
+ return "node";
2283
+ }
2284
+ if (schema.marks[name]) {
2285
+ return "mark";
2286
+ }
2287
+ return null;
2288
+ }
2289
+ function deleteProps(obj, propOrProps) {
2290
+ const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps;
2291
+ return Object.keys(obj).reduce((newObj, prop) => {
2292
+ if (!props.includes(prop)) {
2293
+ newObj[prop] = obj[prop];
2294
+ }
2295
+ return newObj;
2296
+ }, {});
2297
+ }
2298
+ var resetAttributes = (typeOrName, attributes) => ({ tr, state, dispatch }) => {
2299
+ let nodeType = null;
2300
+ let markType = null;
2301
+ const schemaType = getSchemaTypeNameByName(
2302
+ typeof typeOrName === "string" ? typeOrName : typeOrName.name,
2303
+ state.schema
2304
+ );
2305
+ if (!schemaType) {
2306
+ return false;
2307
+ }
2308
+ if (schemaType === "node") {
2309
+ nodeType = getNodeType(typeOrName, state.schema);
2310
+ }
2311
+ if (schemaType === "mark") {
2312
+ markType = getMarkType(typeOrName, state.schema);
2313
+ }
2314
+ let canReset = false;
2315
+ tr.selection.ranges.forEach((range) => {
2316
+ state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {
2317
+ if (nodeType && nodeType === node.type) {
2318
+ canReset = true;
2319
+ if (dispatch) {
2320
+ tr.setNodeMarkup(pos, void 0, deleteProps(node.attrs, attributes));
2321
+ }
2322
+ }
2323
+ if (markType && node.marks.length) {
2324
+ node.marks.forEach((mark) => {
2325
+ if (markType === mark.type) {
2326
+ canReset = true;
2327
+ if (dispatch) {
2328
+ tr.addMark(
2329
+ pos,
2330
+ pos + node.nodeSize,
2331
+ markType.create(deleteProps(mark.attrs, attributes))
2332
+ );
2333
+ }
2334
+ }
2335
+ });
2336
+ }
2337
+ });
2338
+ });
2339
+ return canReset;
2340
+ };
2341
+ var scrollIntoView = () => ({ tr, dispatch }) => {
2342
+ if (dispatch) {
2343
+ tr.scrollIntoView();
2344
+ }
2345
+ return true;
2346
+ };
2347
+ var selectAll = () => ({ tr, dispatch }) => {
2348
+ if (dispatch) {
2349
+ const selection = new state.AllSelection(tr.doc);
2350
+ tr.setSelection(selection);
2351
+ }
2352
+ return true;
2353
+ };
2354
+ var selectNodeBackward = () => ({ state, dispatch }) => {
2355
+ return commands.selectNodeBackward(state, dispatch);
2356
+ };
2357
+ var selectNodeForward = () => ({ state, dispatch }) => {
2358
+ return commands.selectNodeForward(state, dispatch);
2359
+ };
2360
+ var selectParentNode = () => ({ state, dispatch }) => {
2361
+ return commands.selectParentNode(state, dispatch);
2362
+ };
2363
+ var selectTextblockEnd = () => ({ state, dispatch }) => {
2364
+ return commands.selectTextblockEnd(state, dispatch);
2365
+ };
2366
+ var selectTextblockStart = () => ({ state, dispatch }) => {
2367
+ return commands.selectTextblockStart(state, dispatch);
2368
+ };
2369
+ function createDocument(content, schema, parseOptions = {}, options = {}) {
2370
+ return createNodeFromContent(content, schema, {
2371
+ slice: false,
2372
+ parseOptions,
2373
+ errorOnInvalidContent: options.errorOnInvalidContent
2374
+ });
2375
+ }
2376
+ var setContent = (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) => ({ editor, tr, dispatch, commands }) => {
2377
+ const { doc } = tr;
2378
+ if (parseOptions.preserveWhitespace !== "full") {
2379
+ const document2 = createDocument(content, editor.schema, parseOptions, {
2380
+ errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck
2381
+ });
2382
+ if (dispatch) {
2383
+ tr.replaceWith(0, doc.content.size, document2).setMeta("preventUpdate", !emitUpdate);
2384
+ }
2385
+ return true;
2386
+ }
2387
+ if (dispatch) {
2388
+ tr.setMeta("preventUpdate", !emitUpdate);
2389
+ }
2390
+ return commands.insertContentAt({ from: 0, to: doc.content.size }, content, {
2391
+ parseOptions,
2392
+ errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck
2393
+ });
2394
+ };
2395
+ function getMarkAttributes(state, typeOrName) {
2396
+ const type = getMarkType(typeOrName, state.schema);
2397
+ const { from, to, empty } = state.selection;
2398
+ const marks = [];
2399
+ if (empty) {
2400
+ if (state.storedMarks) {
2401
+ marks.push(...state.storedMarks);
2402
+ }
2403
+ marks.push(...state.selection.$head.marks());
2404
+ } else {
2405
+ state.doc.nodesBetween(from, to, (node) => {
2406
+ marks.push(...node.marks);
2407
+ });
2408
+ }
2409
+ const mark = marks.find((markItem) => markItem.type.name === type.name);
2410
+ if (!mark) {
2411
+ return {};
2412
+ }
2413
+ return { ...mark.attrs };
2414
+ }
2415
+ function combineTransactionSteps(oldDoc, transactions) {
2416
+ const transform$1 = new transform.Transform(oldDoc);
2417
+ transactions.forEach((transaction) => {
2418
+ transaction.steps.forEach((step) => {
2419
+ transform$1.step(step);
2420
+ });
2421
+ });
2422
+ return transform$1;
2423
+ }
2424
+ function defaultBlockAt(match) {
2425
+ for (let i = 0; i < match.edgeCount; i += 1) {
2426
+ const { type } = match.edge(i);
2427
+ if (type.isTextblock && !type.hasRequiredAttrs()) {
2428
+ return type;
2429
+ }
2430
+ }
2431
+ return null;
2432
+ }
2433
+ function findParentNodeClosestToPos($pos, predicate) {
2434
+ for (let i = $pos.depth; i > 0; i -= 1) {
2435
+ const node = $pos.node(i);
2436
+ if (predicate(node)) {
2437
+ return {
2438
+ pos: i > 0 ? $pos.before(i) : 0,
2439
+ start: $pos.start(i),
2440
+ depth: i,
2441
+ node
2442
+ };
2443
+ }
2444
+ }
2445
+ }
2446
+ function findParentNode(predicate) {
2447
+ return (selection) => findParentNodeClosestToPos(selection.$from, predicate);
2448
+ }
2449
+ function getExtensionField(extension, field, context) {
2450
+ if (extension.config[field] === void 0 && extension.parent) {
2451
+ return getExtensionField(extension.parent, field, context);
2452
+ }
2453
+ if (typeof extension.config[field] === "function") {
2454
+ const value = extension.config[field].bind({
2455
+ ...context,
2456
+ parent: extension.parent ? getExtensionField(extension.parent, field, context) : null
2457
+ });
2458
+ return value;
2459
+ }
2460
+ return extension.config[field];
2461
+ }
2462
+ function isFunction(value) {
2463
+ return typeof value === "function";
2464
+ }
2465
+ function callOrReturn(value, context = void 0, ...props) {
2466
+ if (isFunction(value)) {
2467
+ if (context) {
2468
+ return value.bind(context)(...props);
2469
+ }
2470
+ return value(...props);
2471
+ }
2472
+ return value;
2473
+ }
2474
+ function splitExtensions(extensions) {
2475
+ const baseExtensions = extensions.filter(
2476
+ (extension) => extension.type === "extension"
2477
+ );
2478
+ const nodeExtensions = extensions.filter((extension) => extension.type === "node");
2479
+ const markExtensions = extensions.filter((extension) => extension.type === "mark");
2480
+ return {
2481
+ baseExtensions,
2482
+ nodeExtensions,
2483
+ markExtensions
2484
+ };
2485
+ }
2486
+ function splitStyleDeclarations(styles) {
2487
+ const result = [];
2488
+ let current = "";
2489
+ let inSingleQuote = false;
2490
+ let inDoubleQuote = false;
2491
+ let parenDepth = 0;
2492
+ const length = styles.length;
2493
+ for (let i = 0; i < length; i += 1) {
2494
+ const char = styles[i];
2495
+ if (char === "'" && !inDoubleQuote) {
2496
+ inSingleQuote = !inSingleQuote;
2497
+ current += char;
2498
+ continue;
2499
+ }
2500
+ if (char === '"' && !inSingleQuote) {
2501
+ inDoubleQuote = !inDoubleQuote;
2502
+ current += char;
2503
+ continue;
2504
+ }
2505
+ if (!inSingleQuote && !inDoubleQuote) {
2506
+ if (char === "(") {
2507
+ parenDepth += 1;
2508
+ current += char;
2509
+ continue;
2510
+ }
2511
+ if (char === ")" && parenDepth > 0) {
2512
+ parenDepth -= 1;
2513
+ current += char;
2514
+ continue;
2515
+ }
2516
+ if (char === ";" && parenDepth === 0) {
2517
+ result.push(current);
2518
+ current = "";
2519
+ continue;
2520
+ }
2521
+ }
2522
+ current += char;
2523
+ }
2524
+ if (current) {
2525
+ result.push(current);
2526
+ }
2527
+ return result;
2528
+ }
2529
+ function parseStyleEntries(styles) {
2530
+ const pairs = [];
2531
+ const declarations = splitStyleDeclarations(styles || "");
2532
+ const numDeclarations = declarations.length;
2533
+ for (let i = 0; i < numDeclarations; i += 1) {
2534
+ const declaration = declarations[i];
2535
+ const firstColonIndex = declaration.indexOf(":");
2536
+ if (firstColonIndex === -1) {
2537
+ continue;
2538
+ }
2539
+ const property = declaration.slice(0, firstColonIndex).trim();
2540
+ const value = declaration.slice(firstColonIndex + 1).trim();
2541
+ if (property && value) {
2542
+ pairs.push([property, value]);
2543
+ }
2544
+ }
2545
+ return pairs;
2546
+ }
2547
+ function mergeAttributes(...objects) {
2548
+ return objects.filter((item) => !!item).reduce((items, item) => {
2549
+ const mergedAttributes = { ...items };
2550
+ Object.entries(item).forEach(([key, value]) => {
2551
+ const exists = mergedAttributes[key];
2552
+ if (!exists) {
2553
+ mergedAttributes[key] = value;
2554
+ return;
2555
+ }
2556
+ if (key === "class") {
2557
+ const valueClasses = value ? String(value).split(" ") : [];
2558
+ const existingClasses = mergedAttributes[key] ? mergedAttributes[key].split(" ") : [];
2559
+ const insertClasses = valueClasses.filter(
2560
+ (valueClass) => !existingClasses.includes(valueClass)
2561
+ );
2562
+ mergedAttributes[key] = [...existingClasses, ...insertClasses].join(" ");
2563
+ } else if (key === "style") {
2564
+ const styleMap = new Map([
2565
+ ...parseStyleEntries(mergedAttributes[key]),
2566
+ ...parseStyleEntries(value)
2567
+ ]);
2568
+ mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join("; ");
2569
+ } else {
2570
+ mergedAttributes[key] = value;
2571
+ }
2572
+ });
2573
+ return mergedAttributes;
2574
+ }, {});
2575
+ }
2576
+ function getTextBetween(startNode, range, options) {
2577
+ const { from, to } = range;
2578
+ const { blockSeparator = "\n\n", textSerializers = {} } = options || {};
2579
+ let text = "";
2580
+ startNode.nodesBetween(from, to, (node, pos, parent, index) => {
2581
+ var _a;
2582
+ if (node.isBlock && pos > from) {
2583
+ text += blockSeparator;
2584
+ }
2585
+ const textSerializer = textSerializers == null ? void 0 : textSerializers[node.type.name];
2586
+ if (textSerializer) {
2587
+ if (parent) {
2588
+ text += textSerializer({
2589
+ node,
2590
+ pos,
2591
+ parent,
2592
+ index,
2593
+ range
2594
+ });
2595
+ }
2596
+ return false;
2597
+ }
2598
+ if (node.isText) {
2599
+ text += (_a = node == null ? void 0 : node.text) == null ? void 0 : _a.slice(Math.max(from, pos) - pos, to - pos);
2600
+ }
2601
+ });
2602
+ return text;
2603
+ }
2604
+ function getTextSerializersFromSchema(schema) {
2605
+ return Object.fromEntries(
2606
+ Object.entries(schema.nodes).filter(([, node]) => node.spec.toText).map(([name, node]) => [name, node.spec.toText])
2607
+ );
2608
+ }
2609
+ function removeDuplicates(array, by = JSON.stringify) {
2610
+ const seen = {};
2611
+ return array.filter((item) => {
2612
+ const key = by(item);
2613
+ return Object.prototype.hasOwnProperty.call(seen, key) ? false : seen[key] = true;
2614
+ });
2615
+ }
2616
+ function simplifyChangedRanges(changes) {
2617
+ const uniqueChanges = removeDuplicates(changes);
2618
+ return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index) => {
2619
+ const rest = uniqueChanges.filter((_, i) => i !== index);
2620
+ return !rest.some((otherChange) => {
2621
+ return change.oldRange.from >= otherChange.oldRange.from && change.oldRange.to <= otherChange.oldRange.to && change.newRange.from >= otherChange.newRange.from && change.newRange.to <= otherChange.newRange.to;
2622
+ });
2623
+ });
2624
+ }
2625
+ function getChangedRanges(transform) {
2626
+ const { mapping, steps } = transform;
2627
+ const changes = [];
2628
+ mapping.maps.forEach((stepMap, index) => {
2629
+ const ranges = [];
2630
+ if (!stepMap.ranges.length) {
2631
+ const { from, to } = steps[index];
2632
+ if (from === void 0 || to === void 0) {
2633
+ return;
2634
+ }
2635
+ ranges.push({ from, to });
2636
+ } else {
2637
+ stepMap.forEach((from, to) => {
2638
+ ranges.push({ from, to });
2639
+ });
2640
+ }
2641
+ ranges.forEach(({ from, to }) => {
2642
+ const newStart = mapping.slice(index).map(from, -1);
2643
+ const newEnd = mapping.slice(index).map(to);
2644
+ const oldStart = mapping.invert().map(newStart, -1);
2645
+ const oldEnd = mapping.invert().map(newEnd);
2646
+ changes.push({
2647
+ oldRange: {
2648
+ from: oldStart,
2649
+ to: oldEnd
2650
+ },
2651
+ newRange: {
2652
+ from: newStart,
2653
+ to: newEnd
2654
+ }
2655
+ });
2656
+ });
2657
+ });
2658
+ return simplifyChangedRanges(changes);
2659
+ }
2660
+ function getSplittedAttributes(extensionAttributes, typeName, attributes) {
2661
+ return Object.fromEntries(
2662
+ Object.entries(attributes).filter(([name]) => {
2663
+ const extensionAttribute = extensionAttributes.find((item) => {
2664
+ return item.type === typeName && item.name === name;
2665
+ });
2666
+ if (!extensionAttribute) {
2667
+ return false;
2668
+ }
2669
+ return extensionAttribute.attribute.keepOnSplit;
2670
+ })
2671
+ );
2672
+ }
2673
+ function isMarkActive(state, typeOrName, attributes = {}) {
2674
+ const { empty, ranges } = state.selection;
2675
+ const type = typeOrName ? getMarkType(typeOrName, state.schema) : null;
2676
+ if (empty) {
2677
+ return !!(state.storedMarks || state.selection.$from.marks()).filter((mark) => {
2678
+ if (!type) {
2679
+ return true;
2680
+ }
2681
+ return type.name === mark.type.name;
2682
+ }).find((mark) => objectIncludes(mark.attrs, attributes, { strict: false }));
2683
+ }
2684
+ let selectionRange = 0;
2685
+ const markRanges = [];
2686
+ ranges.forEach(({ $from, $to }) => {
2687
+ const from = $from.pos;
2688
+ const to = $to.pos;
2689
+ state.doc.nodesBetween(from, to, (node, pos) => {
2690
+ if (type && node.inlineContent && !node.type.allowsMarkType(type)) {
2691
+ return false;
2692
+ }
2693
+ if (!node.isText && !node.marks.length) {
2694
+ return;
2695
+ }
2696
+ const relativeFrom = Math.max(from, pos);
2697
+ const relativeTo = Math.min(to, pos + node.nodeSize);
2698
+ const range2 = relativeTo - relativeFrom;
2699
+ selectionRange += range2;
2700
+ markRanges.push(
2701
+ ...node.marks.map((mark) => ({
2702
+ mark,
2703
+ from: relativeFrom,
2704
+ to: relativeTo
2705
+ }))
2706
+ );
2707
+ });
2708
+ });
2709
+ if (selectionRange === 0) {
2710
+ return false;
2711
+ }
2712
+ const matchedRange = markRanges.filter((markRange) => {
2713
+ if (!type) {
2714
+ return true;
2715
+ }
2716
+ return type.name === markRange.mark.type.name;
2717
+ }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
2718
+ const excludedRange = markRanges.filter((markRange) => {
2719
+ if (!type) {
2720
+ return true;
2721
+ }
2722
+ return markRange.mark.type !== type && markRange.mark.type.excludes(type);
2723
+ }).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
2724
+ const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange;
2725
+ return range >= selectionRange;
2726
+ }
2727
+ function isList(name, extensions) {
2728
+ const { nodeExtensions } = splitExtensions(extensions);
2729
+ const extension = nodeExtensions.find((item) => item.name === name);
2730
+ if (!extension) {
2731
+ return false;
2732
+ }
2733
+ const context = {
2734
+ name: extension.name,
2735
+ options: extension.options,
2736
+ storage: extension.storage
2737
+ };
2738
+ const group = callOrReturn(getExtensionField(extension, "group", context));
2739
+ if (typeof group !== "string") {
2740
+ return false;
2741
+ }
2742
+ return group.split(" ").includes("list");
2743
+ }
2744
+ function isNodeEmpty(node, {
2745
+ checkChildren = true,
2746
+ ignoreWhitespace = false
2747
+ } = {}) {
2748
+ var _a;
2749
+ if (ignoreWhitespace) {
2750
+ if (node.type.name === "hardBreak") {
2751
+ return true;
2752
+ }
2753
+ if (node.isText) {
2754
+ return !/\S/.test((_a = node.text) != null ? _a : "");
2755
+ }
2756
+ }
2757
+ if (node.isText) {
2758
+ return !node.text;
2759
+ }
2760
+ if (node.isAtom || node.isLeaf) {
2761
+ return false;
2762
+ }
2763
+ if (node.content.childCount === 0) {
2764
+ return true;
2765
+ }
2766
+ if (checkChildren) {
2767
+ let isContentEmpty = true;
2768
+ node.content.forEach((childNode) => {
2769
+ if (isContentEmpty === false) {
2770
+ return;
2771
+ }
2772
+ if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {
2773
+ isContentEmpty = false;
2774
+ }
2775
+ });
2776
+ return isContentEmpty;
2777
+ }
2778
+ return false;
2779
+ }
2780
+ function canSetMark(state, tr, newMarkType) {
2781
+ var _a;
2782
+ const { selection } = tr;
2783
+ let cursor = null;
2784
+ if (isTextSelection(selection)) {
2785
+ cursor = selection.$cursor;
2786
+ }
2787
+ if (cursor) {
2788
+ const currentMarks = (_a = state.storedMarks) != null ? _a : cursor.marks();
2789
+ const parentAllowsMarkType = cursor.parent.type.allowsMarkType(newMarkType);
2790
+ return parentAllowsMarkType && (!!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark) => mark.type.excludes(newMarkType)));
2791
+ }
2792
+ const { ranges } = selection;
2793
+ return ranges.some(({ $from, $to }) => {
2794
+ let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false;
2795
+ state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => {
2796
+ if (someNodeSupportsMark) {
2797
+ return false;
2798
+ }
2799
+ if (node.isInline) {
2800
+ const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType);
2801
+ const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks) || !node.marks.some((otherMark) => otherMark.type.excludes(newMarkType));
2802
+ someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType;
2803
+ }
2804
+ return !someNodeSupportsMark;
2805
+ });
2806
+ return someNodeSupportsMark;
2807
+ });
2808
+ }
2809
+ var setMark = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
2810
+ const { selection } = tr;
2811
+ const { empty, ranges } = selection;
2812
+ const type = getMarkType(typeOrName, state.schema);
2813
+ if (dispatch) {
2814
+ if (empty) {
2815
+ const oldAttributes = getMarkAttributes(state, type);
2816
+ tr.addStoredMark(
2817
+ type.create({
2818
+ ...oldAttributes,
2819
+ ...attributes
2820
+ })
2821
+ );
2822
+ } else {
2823
+ ranges.forEach((range) => {
2824
+ const from = range.$from.pos;
2825
+ const to = range.$to.pos;
2826
+ state.doc.nodesBetween(from, to, (node, pos) => {
2827
+ const trimmedFrom = Math.max(pos, from);
2828
+ const trimmedTo = Math.min(pos + node.nodeSize, to);
2829
+ const someHasMark = node.marks.find((mark) => mark.type === type);
2830
+ if (someHasMark) {
2831
+ node.marks.forEach((mark) => {
2832
+ if (type === mark.type) {
2833
+ tr.addMark(
2834
+ trimmedFrom,
2835
+ trimmedTo,
2836
+ type.create({
2837
+ ...mark.attrs,
2838
+ ...attributes
2839
+ })
2840
+ );
2841
+ }
2842
+ });
2843
+ } else {
2844
+ tr.addMark(trimmedFrom, trimmedTo, type.create(attributes));
2845
+ }
2846
+ });
2847
+ });
2848
+ }
2849
+ }
2850
+ return canSetMark(state, tr, type);
2851
+ };
2852
+ var setMeta = (key, value) => ({ tr }) => {
2853
+ tr.setMeta(key, value);
2854
+ return true;
2855
+ };
2856
+ var setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => {
2857
+ const type = getNodeType(typeOrName, state.schema);
2858
+ let attributesToCopy;
2859
+ if (state.selection.$anchor.sameParent(state.selection.$head)) {
2860
+ attributesToCopy = state.selection.$anchor.parent.attrs;
2861
+ }
2862
+ if (!type.isTextblock) {
2863
+ console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.');
2864
+ return false;
2865
+ }
2866
+ return chain().command(({ commands: commands$1 }) => {
2867
+ const canSetBlock = commands.setBlockType(type, { ...attributesToCopy, ...attributes })(state);
2868
+ if (canSetBlock) {
2869
+ return true;
2870
+ }
2871
+ return commands$1.clearNodes();
2872
+ }).command(({ state: updatedState }) => {
2873
+ return commands.setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch);
2874
+ }).run();
2875
+ };
2876
+ var setNodeSelection = (position) => ({ tr, dispatch }) => {
2877
+ if (dispatch) {
2878
+ const { doc } = tr;
2879
+ const from = minMax(position, 0, doc.content.size);
2880
+ const selection = state.NodeSelection.create(doc, from);
2881
+ tr.setSelection(selection);
2882
+ }
2883
+ return true;
2884
+ };
2885
+ var setTextDirection = (direction, position) => ({ tr, state, dispatch }) => {
2886
+ const { selection } = state;
2887
+ let from;
2888
+ let to;
2889
+ if (typeof position === "number") {
2890
+ from = position;
2891
+ to = position;
2892
+ } else if (position && "from" in position && "to" in position) {
2893
+ from = position.from;
2894
+ to = position.to;
2895
+ } else {
2896
+ from = selection.from;
2897
+ to = selection.to;
2898
+ }
2899
+ if (dispatch) {
2900
+ tr.doc.nodesBetween(from, to, (node, pos) => {
2901
+ if (node.isText) {
2902
+ return;
2903
+ }
2904
+ tr.setNodeMarkup(pos, void 0, {
2905
+ ...node.attrs,
2906
+ dir: direction
2907
+ });
2908
+ });
2909
+ }
2910
+ return true;
2911
+ };
2912
+ var setTextSelection = (position) => ({ tr, dispatch }) => {
2913
+ if (dispatch) {
2914
+ const { doc } = tr;
2915
+ const { from, to } = typeof position === "number" ? { from: position, to: position } : position;
2916
+ const minPos = state.TextSelection.atStart(doc).from;
2917
+ const maxPos = state.TextSelection.atEnd(doc).to;
2918
+ const resolvedFrom = minMax(from, minPos, maxPos);
2919
+ const resolvedEnd = minMax(to, minPos, maxPos);
2920
+ const selection = state.TextSelection.create(doc, resolvedFrom, resolvedEnd);
2921
+ tr.setSelection(selection);
2922
+ }
2923
+ return true;
2924
+ };
2925
+ var sinkListItem = (typeOrName) => ({ state, dispatch }) => {
2926
+ const type = getNodeType(typeOrName, state.schema);
2927
+ return schemaList.sinkListItem(type)(state, dispatch);
2928
+ };
2929
+ function ensureMarks(state, splittableMarks) {
2930
+ const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();
2931
+ if (marks) {
2932
+ const filteredMarks = marks.filter((mark) => splittableMarks == null ? void 0 : splittableMarks.includes(mark.type.name));
2933
+ state.tr.ensureMarks(filteredMarks);
2934
+ }
2935
+ }
2936
+ var splitBlock = ({ keepMarks = true } = {}) => ({ tr, state: state$1, dispatch, editor }) => {
2937
+ const { selection, doc } = tr;
2938
+ const { $from, $to } = selection;
2939
+ const extensionAttributes = editor.extensionManager.attributes;
2940
+ const newAttributes = getSplittedAttributes(
2941
+ extensionAttributes,
2942
+ $from.node().type.name,
2943
+ $from.node().attrs
2944
+ );
2945
+ if (selection instanceof state.NodeSelection && selection.node.isBlock) {
2946
+ if (!$from.parentOffset || !transform.canSplit(doc, $from.pos)) {
2947
+ return false;
2948
+ }
2949
+ if (dispatch) {
2950
+ if (keepMarks) {
2951
+ ensureMarks(state$1, editor.extensionManager.splittableMarks);
2952
+ }
2953
+ tr.split($from.pos).scrollIntoView();
2954
+ }
2955
+ return true;
2956
+ }
2957
+ if (!$from.parent.isBlock) {
2958
+ return false;
2959
+ }
2960
+ const atEnd = $to.parentOffset === $to.parent.content.size;
2961
+ const deflt = $from.depth === 0 ? void 0 : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));
2962
+ let types = atEnd && deflt ? [
2963
+ {
2964
+ type: deflt,
2965
+ attrs: newAttributes
2966
+ }
2967
+ ] : void 0;
2968
+ let can = transform.canSplit(tr.doc, tr.mapping.map($from.pos), 1, types);
2969
+ if (!types && !can && transform.canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) {
2970
+ can = true;
2971
+ types = deflt ? [
2972
+ {
2973
+ type: deflt,
2974
+ attrs: newAttributes
2975
+ }
2976
+ ] : void 0;
2977
+ }
2978
+ if (dispatch) {
2979
+ if (can) {
2980
+ if (selection instanceof state.TextSelection) {
2981
+ tr.deleteSelection();
2982
+ }
2983
+ tr.split(tr.mapping.map($from.pos), 1, types);
2984
+ if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {
2985
+ const first2 = tr.mapping.map($from.before());
2986
+ const $first = tr.doc.resolve(first2);
2987
+ if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {
2988
+ tr.setNodeMarkup(tr.mapping.map($from.before()), deflt);
2989
+ }
2990
+ }
2991
+ }
2992
+ if (keepMarks) {
2993
+ ensureMarks(state$1, editor.extensionManager.splittableMarks);
2994
+ }
2995
+ tr.scrollIntoView();
2996
+ }
2997
+ return can;
2998
+ };
2999
+ var splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr, state: state$1, dispatch, editor }) => {
3000
+ var _a;
3001
+ const type = getNodeType(typeOrName, state$1.schema);
3002
+ const { $from, $to } = state$1.selection;
3003
+ const node = state$1.selection.node;
3004
+ if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) {
3005
+ return false;
3006
+ }
3007
+ const grandParent = $from.node(-1);
3008
+ if (grandParent.type !== type) {
3009
+ return false;
3010
+ }
3011
+ const extensionAttributes = editor.extensionManager.attributes;
3012
+ if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {
3013
+ if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) {
3014
+ return false;
3015
+ }
3016
+ if (dispatch) {
3017
+ let wrap = model.Fragment.empty;
3018
+ const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;
3019
+ for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {
3020
+ wrap = model.Fragment.from($from.node(d).copy(wrap));
3021
+ }
3022
+ const depthAfter = (
3023
+ // oxlint-disable-next-line no-nested-ternary
3024
+ $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3
3025
+ );
3026
+ const newNextTypeAttributes2 = {
3027
+ ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
3028
+ ...overrideAttrs
3029
+ };
3030
+ const nextType2 = ((_a = type.contentMatch.defaultType) == null ? void 0 : _a.createAndFill(newNextTypeAttributes2)) || void 0;
3031
+ wrap = wrap.append(model.Fragment.from(type.createAndFill(null, nextType2) || void 0));
3032
+ const start = $from.before($from.depth - (depthBefore - 1));
3033
+ tr.replace(start, $from.after(-depthAfter), new model.Slice(wrap, 4 - depthBefore, 0));
3034
+ let sel = -1;
3035
+ tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {
3036
+ if (sel > -1) {
3037
+ return false;
3038
+ }
3039
+ if (n.isTextblock && n.content.size === 0) {
3040
+ sel = pos + 1;
3041
+ }
3042
+ });
3043
+ if (sel > -1) {
3044
+ tr.setSelection(state.TextSelection.near(tr.doc.resolve(sel)));
3045
+ }
3046
+ tr.scrollIntoView();
3047
+ }
3048
+ return true;
3049
+ }
3050
+ const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
3051
+ const newTypeAttributes = {
3052
+ ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),
3053
+ ...overrideAttrs
3054
+ };
3055
+ const newNextTypeAttributes = {
3056
+ ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
3057
+ ...overrideAttrs
3058
+ };
3059
+ tr.delete($from.pos, $to.pos);
3060
+ const types = nextType ? [
3061
+ { type, attrs: newTypeAttributes },
3062
+ { type: nextType, attrs: newNextTypeAttributes }
3063
+ ] : [{ type, attrs: newTypeAttributes }];
3064
+ if (!transform.canSplit(tr.doc, $from.pos, 2)) {
3065
+ return false;
3066
+ }
3067
+ if (dispatch) {
3068
+ const { selection, storedMarks } = state$1;
3069
+ const { splittableMarks } = editor.extensionManager;
3070
+ const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
3071
+ tr.split($from.pos, 2, types).scrollIntoView();
3072
+ if (!marks || !dispatch) {
3073
+ return true;
3074
+ }
3075
+ const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
3076
+ tr.ensureMarks(filteredMarks);
3077
+ }
3078
+ return true;
3079
+ };
3080
+ var joinListBackwards = (tr, listType) => {
3081
+ const list = findParentNode((node) => node.type === listType)(tr.selection);
3082
+ if (!list) {
3083
+ return true;
3084
+ }
3085
+ const before = tr.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth);
3086
+ if (before === void 0) {
3087
+ return true;
3088
+ }
3089
+ const nodeBefore = tr.doc.nodeAt(before);
3090
+ const canJoinBackwards = list.node.type === (nodeBefore == null ? void 0 : nodeBefore.type) && transform.canJoin(tr.doc, list.pos);
3091
+ if (!canJoinBackwards) {
3092
+ return true;
3093
+ }
3094
+ tr.join(list.pos);
3095
+ return true;
3096
+ };
3097
+ var joinListForwards = (tr, listType) => {
3098
+ const list = findParentNode((node) => node.type === listType)(tr.selection);
3099
+ if (!list) {
3100
+ return true;
3101
+ }
3102
+ const after = tr.doc.resolve(list.start).after(list.depth);
3103
+ if (after === void 0) {
3104
+ return true;
3105
+ }
3106
+ const nodeAfter = tr.doc.nodeAt(after);
3107
+ const canJoinForwards = list.node.type === (nodeAfter == null ? void 0 : nodeAfter.type) && transform.canJoin(tr.doc, after);
3108
+ if (!canJoinForwards) {
3109
+ return true;
3110
+ }
3111
+ tr.join(after);
3112
+ return true;
3113
+ };
3114
+ function createInnerSelectionForWholeDocList(tr) {
3115
+ const doc = tr.doc;
3116
+ const list = doc.firstChild;
3117
+ if (!list) {
3118
+ return null;
3119
+ }
3120
+ const $start = doc.resolve(1);
3121
+ const $end = doc.resolve(list.nodeSize - 1);
3122
+ return state.TextSelection.between($start, $end);
3123
+ }
3124
+ var toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr, state, dispatch, chain, commands, can }) => {
3125
+ const { extensions, splittableMarks } = editor.extensionManager;
3126
+ const listType = getNodeType(listTypeOrName, state.schema);
3127
+ const itemType = getNodeType(itemTypeOrName, state.schema);
3128
+ const { selection, storedMarks } = state;
3129
+ const { $from, $to } = selection;
3130
+ const range = $from.blockRange($to);
3131
+ const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
3132
+ if (!range) {
3133
+ return false;
3134
+ }
3135
+ const parentList = findParentNode((node) => isList(node.type.name, extensions))(selection);
3136
+ const isAllSelection = selection.from === 0 && selection.to === state.doc.content.size;
3137
+ const topLevelNodes = state.doc.content.content;
3138
+ const soleTopLevelNode = topLevelNodes.length === 1 ? topLevelNodes[0] : null;
3139
+ const allSelectionList = isAllSelection && soleTopLevelNode && isList(soleTopLevelNode.type.name, extensions) ? {
3140
+ node: soleTopLevelNode,
3141
+ pos: 0} : null;
3142
+ const currentList = parentList != null ? parentList : allSelectionList;
3143
+ const isInsideExistingList = !!parentList && range.depth >= 1 && range.depth - parentList.depth <= 1;
3144
+ const hasWholeDocSelectedList = !!allSelectionList;
3145
+ if ((isInsideExistingList || hasWholeDocSelectedList) && currentList) {
3146
+ if (currentList.node.type === listType) {
3147
+ if (isAllSelection && hasWholeDocSelectedList) {
3148
+ return chain().command(({ tr: trx, dispatch: disp }) => {
3149
+ const nextSelection = createInnerSelectionForWholeDocList(trx);
3150
+ if (!nextSelection) {
3151
+ return false;
3152
+ }
3153
+ trx.setSelection(nextSelection);
3154
+ if (disp) {
3155
+ disp(trx);
3156
+ }
3157
+ return true;
3158
+ }).liftListItem(itemType).run();
3159
+ }
3160
+ return commands.liftListItem(itemType);
3161
+ }
3162
+ if (isList(currentList.node.type.name, extensions) && listType.validContent(currentList.node.content)) {
3163
+ return chain().command(() => {
3164
+ tr.setNodeMarkup(currentList.pos, listType);
3165
+ return true;
3166
+ }).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
3167
+ }
3168
+ }
3169
+ if (!keepMarks || !marks || !dispatch) {
3170
+ return chain().command(() => {
3171
+ const canWrapInList = can().wrapInList(listType, attributes);
3172
+ if (canWrapInList) {
3173
+ return true;
3174
+ }
3175
+ return commands.clearNodes();
3176
+ }).wrapInList(listType, attributes).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
3177
+ }
3178
+ return chain().command(() => {
3179
+ const canWrapInList = can().wrapInList(listType, attributes);
3180
+ const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
3181
+ tr.ensureMarks(filteredMarks);
3182
+ if (canWrapInList) {
3183
+ return true;
3184
+ }
3185
+ return commands.clearNodes();
3186
+ }).wrapInList(listType, attributes).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
3187
+ };
3188
+ var toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => {
3189
+ const { extendEmptyMarkRange = false } = options;
3190
+ const type = getMarkType(typeOrName, state.schema);
3191
+ const isActive2 = isMarkActive(state, type, attributes);
3192
+ if (isActive2) {
3193
+ return commands.unsetMark(type, { extendEmptyMarkRange });
3194
+ }
3195
+ return commands.setMark(type, attributes);
3196
+ };
3197
+ var toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => {
3198
+ const type = getNodeType(typeOrName, state.schema);
3199
+ const toggleType = getNodeType(toggleTypeOrName, state.schema);
3200
+ const isActive2 = isNodeActive(state, type, attributes);
3201
+ let attributesToCopy;
3202
+ if (state.selection.$anchor.sameParent(state.selection.$head)) {
3203
+ attributesToCopy = state.selection.$anchor.parent.attrs;
3204
+ }
3205
+ if (isActive2) {
3206
+ return commands.setNode(toggleType, attributesToCopy);
3207
+ }
3208
+ return commands.setNode(type, { ...attributesToCopy, ...attributes });
3209
+ };
3210
+ var toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => {
3211
+ const type = getNodeType(typeOrName, state.schema);
3212
+ const isActive2 = isNodeActive(state, type, attributes);
3213
+ if (isActive2) {
3214
+ return commands.lift(type);
3215
+ }
3216
+ return commands.wrapIn(type, attributes);
3217
+ };
3218
+ var undoInputRule = () => ({ state, dispatch }) => {
3219
+ const plugins = state.plugins;
3220
+ for (let i = 0; i < plugins.length; i += 1) {
3221
+ const plugin = plugins[i];
3222
+ let undoable;
3223
+ if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
3224
+ if (dispatch) {
3225
+ const tr = state.tr;
3226
+ const toUndo = undoable.transform;
3227
+ for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {
3228
+ tr.step(toUndo.steps[j].invert(toUndo.docs[j]));
3229
+ }
3230
+ if (undoable.text) {
3231
+ const marks = tr.doc.resolve(undoable.from).marks();
3232
+ tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));
3233
+ } else {
3234
+ tr.delete(undoable.from, undoable.to);
3235
+ }
3236
+ }
3237
+ return true;
3238
+ }
3239
+ }
3240
+ return false;
3241
+ };
3242
+ var unsetAllMarks = (options = {}) => ({ tr, dispatch, editor }) => {
3243
+ const { ignoreClearable = false } = options;
3244
+ const { selection } = tr;
3245
+ const { empty, ranges } = selection;
3246
+ if (empty) {
3247
+ return true;
3248
+ }
3249
+ const { nonClearableMarks } = editor.extensionManager;
3250
+ if (dispatch) {
3251
+ const clearableMarkTypes = Object.values(editor.schema.marks).filter(
3252
+ (markType) => ignoreClearable || !nonClearableMarks.includes(markType.name)
3253
+ );
3254
+ ranges.forEach((range) => {
3255
+ for (const markType of clearableMarkTypes) {
3256
+ tr.removeMark(range.$from.pos, range.$to.pos, markType);
3257
+ }
3258
+ });
3259
+ }
3260
+ return true;
3261
+ };
3262
+ var unsetMark = (typeOrName, options = {}) => ({ tr, state, dispatch }) => {
3263
+ var _a;
3264
+ const { extendEmptyMarkRange = false } = options;
3265
+ const { selection } = tr;
3266
+ const type = getMarkType(typeOrName, state.schema);
3267
+ const { $from, empty, ranges } = selection;
3268
+ if (!dispatch) {
3269
+ return true;
3270
+ }
3271
+ if (empty && extendEmptyMarkRange) {
3272
+ let { from, to } = selection;
3273
+ const attrs = (_a = $from.marks().find((mark) => mark.type === type)) == null ? void 0 : _a.attrs;
3274
+ const range = getMarkRange($from, type, attrs);
3275
+ if (range) {
3276
+ from = range.from;
3277
+ to = range.to;
3278
+ }
3279
+ tr.removeMark(from, to, type);
3280
+ } else {
3281
+ ranges.forEach((range) => {
3282
+ tr.removeMark(range.$from.pos, range.$to.pos, type);
3283
+ });
3284
+ }
3285
+ tr.removeStoredMark(type);
3286
+ return true;
3287
+ };
3288
+ var unsetTextDirection = (position) => ({ tr, state, dispatch }) => {
3289
+ const { selection } = state;
3290
+ let from;
3291
+ let to;
3292
+ if (typeof position === "number") {
3293
+ from = position;
3294
+ to = position;
3295
+ } else if (position && "from" in position && "to" in position) {
3296
+ from = position.from;
3297
+ to = position.to;
3298
+ } else {
3299
+ from = selection.from;
3300
+ to = selection.to;
3301
+ }
3302
+ if (dispatch) {
3303
+ tr.doc.nodesBetween(from, to, (node, pos) => {
3304
+ if (node.isText) {
3305
+ return;
3306
+ }
3307
+ const newAttrs = { ...node.attrs };
3308
+ delete newAttrs.dir;
3309
+ tr.setNodeMarkup(pos, void 0, newAttrs);
3310
+ });
3311
+ }
3312
+ return true;
3313
+ };
3314
+ var updateAttributes = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
3315
+ let nodeType = null;
3316
+ let markType = null;
3317
+ const schemaType = getSchemaTypeNameByName(
3318
+ typeof typeOrName === "string" ? typeOrName : typeOrName.name,
3319
+ state.schema
3320
+ );
3321
+ if (!schemaType) {
3322
+ return false;
3323
+ }
3324
+ if (schemaType === "node") {
3325
+ nodeType = getNodeType(typeOrName, state.schema);
3326
+ }
3327
+ if (schemaType === "mark") {
3328
+ markType = getMarkType(typeOrName, state.schema);
3329
+ }
3330
+ let canUpdate = false;
3331
+ tr.selection.ranges.forEach((range) => {
3332
+ const from = range.$from.pos;
3333
+ const to = range.$to.pos;
3334
+ let lastPos;
3335
+ let lastNode;
3336
+ let trimmedFrom;
3337
+ let trimmedTo;
3338
+ if (tr.selection.empty) {
3339
+ state.doc.nodesBetween(from, to, (node, pos) => {
3340
+ if (nodeType && nodeType === node.type) {
3341
+ canUpdate = true;
3342
+ trimmedFrom = Math.max(pos, from);
3343
+ trimmedTo = Math.min(pos + node.nodeSize, to);
3344
+ lastPos = pos;
3345
+ lastNode = node;
3346
+ }
3347
+ });
3348
+ } else {
3349
+ state.doc.nodesBetween(from, to, (node, pos) => {
3350
+ if (pos < from && nodeType && nodeType === node.type) {
3351
+ canUpdate = true;
3352
+ trimmedFrom = Math.max(pos, from);
3353
+ trimmedTo = Math.min(pos + node.nodeSize, to);
3354
+ lastPos = pos;
3355
+ lastNode = node;
3356
+ }
3357
+ if (pos >= from && pos <= to) {
3358
+ if (nodeType && nodeType === node.type) {
3359
+ canUpdate = true;
3360
+ if (dispatch) {
3361
+ tr.setNodeMarkup(pos, void 0, {
3362
+ ...node.attrs,
3363
+ ...attributes
3364
+ });
3365
+ }
3366
+ }
3367
+ if (markType && node.marks.length) {
3368
+ node.marks.forEach((mark) => {
3369
+ if (markType === mark.type) {
3370
+ canUpdate = true;
3371
+ if (dispatch) {
3372
+ const trimmedFrom2 = Math.max(pos, from);
3373
+ const trimmedTo2 = Math.min(pos + node.nodeSize, to);
3374
+ tr.addMark(
3375
+ trimmedFrom2,
3376
+ trimmedTo2,
3377
+ markType.create({
3378
+ ...mark.attrs,
3379
+ ...attributes
3380
+ })
3381
+ );
3382
+ }
3383
+ }
3384
+ });
3385
+ }
3386
+ }
3387
+ });
3388
+ }
3389
+ if (lastNode) {
3390
+ if (lastPos !== void 0 && dispatch) {
3391
+ tr.setNodeMarkup(lastPos, void 0, {
3392
+ ...lastNode.attrs,
3393
+ ...attributes
3394
+ });
3395
+ }
3396
+ if (markType && lastNode.marks.length) {
3397
+ lastNode.marks.forEach((mark) => {
3398
+ if (markType === mark.type && dispatch) {
3399
+ tr.addMark(
3400
+ trimmedFrom,
3401
+ trimmedTo,
3402
+ markType.create({
3403
+ ...mark.attrs,
3404
+ ...attributes
3405
+ })
3406
+ );
3407
+ }
3408
+ });
3409
+ }
3410
+ }
3411
+ });
3412
+ return canUpdate;
3413
+ };
3414
+ var wrapIn = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
3415
+ const type = getNodeType(typeOrName, state.schema);
3416
+ return commands.wrapIn(type, attributes)(state, dispatch);
3417
+ };
3418
+ var wrapInList = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
3419
+ const type = getNodeType(typeOrName, state.schema);
3420
+ return schemaList.wrapInList(type, attributes)(state, dispatch);
3421
+ };
3422
+ function getType(value) {
3423
+ return Object.prototype.toString.call(value).slice(8, -1);
3424
+ }
3425
+ function isPlainObject(value) {
3426
+ if (getType(value) !== "Object") {
3427
+ return false;
3428
+ }
3429
+ return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype;
3430
+ }
3431
+ function mergeDeep(target, source) {
3432
+ const output = { ...target };
3433
+ if (isPlainObject(target) && isPlainObject(source)) {
3434
+ Object.keys(source).forEach((key) => {
3435
+ if (isPlainObject(source[key]) && isPlainObject(target[key])) {
3436
+ output[key] = mergeDeep(target[key], source[key]);
3437
+ } else {
3438
+ output[key] = source[key];
3439
+ }
3440
+ });
3441
+ }
3442
+ return output;
3443
+ }
3444
+ var Extendable = class {
3445
+ constructor(config = {}) {
3446
+ this.type = "extendable";
3447
+ this.parent = null;
3448
+ this.child = null;
3449
+ this.name = "";
3450
+ this.config = {
3451
+ name: this.name
3452
+ };
3453
+ this.config = {
3454
+ ...this.config,
3455
+ ...config
3456
+ };
3457
+ this.name = this.config.name;
3458
+ }
3459
+ get options() {
3460
+ return {
3461
+ ...callOrReturn(
3462
+ getExtensionField(this, "addOptions", {
3463
+ name: this.name
3464
+ })
3465
+ )
3466
+ };
3467
+ }
3468
+ get storage() {
3469
+ return {
3470
+ ...callOrReturn(
3471
+ getExtensionField(this, "addStorage", {
3472
+ name: this.name,
3473
+ options: this.options
3474
+ })
3475
+ )
3476
+ };
3477
+ }
3478
+ configure(options = {}) {
3479
+ const extension = this.extend({
3480
+ ...this.config,
3481
+ addOptions: () => {
3482
+ return mergeDeep(this.options, options);
3483
+ }
3484
+ });
3485
+ extension.name = this.name;
3486
+ extension.parent = this.parent;
3487
+ this.child = null;
3488
+ return extension;
3489
+ }
3490
+ extend(extendedConfig = {}) {
3491
+ const extension = new this.constructor({ ...this.config, ...extendedConfig });
3492
+ extension.parent = this;
3493
+ this.child = extension;
3494
+ extension.name = "name" in extendedConfig ? extendedConfig.name : extension.parent.name;
3495
+ return extension;
3496
+ }
3497
+ };
3498
+ var Mark = class _Mark extends Extendable {
3499
+ constructor() {
3500
+ super(...arguments);
3501
+ this.type = "mark";
3502
+ }
3503
+ /**
3504
+ * Create a new Mark instance
3505
+ * @param config - Mark configuration object or a function that returns a configuration object
3506
+ */
3507
+ static create(config = {}) {
3508
+ const resolvedConfig = typeof config === "function" ? config() : config;
3509
+ return new _Mark(resolvedConfig);
3510
+ }
3511
+ static handleExit({ editor, mark }) {
3512
+ const { tr } = editor.state;
3513
+ const currentPos = editor.state.selection.$from;
3514
+ const isAtEnd = currentPos.pos === currentPos.end();
3515
+ if (isAtEnd) {
3516
+ const currentMarks = currentPos.marks();
3517
+ const isInMark = !!currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name);
3518
+ if (!isInMark) {
3519
+ return false;
3520
+ }
3521
+ const removeMark = currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name);
3522
+ if (removeMark) {
3523
+ tr.removeStoredMark(removeMark);
3524
+ }
3525
+ tr.insertText(" ", currentPos.pos);
3526
+ editor.view.dispatch(tr);
3527
+ return true;
3528
+ }
3529
+ return false;
3530
+ }
3531
+ configure(options) {
3532
+ return super.configure(options);
3533
+ }
3534
+ extend(extendedConfig) {
3535
+ const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
3536
+ return super.extend(resolvedConfig);
3537
+ }
3538
+ };
3539
+ var extensions_exports = {};
3540
+ __export(extensions_exports, {
3541
+ ClipboardTextSerializer: () => ClipboardTextSerializer,
3542
+ Commands: () => Commands,
3543
+ Delete: () => Delete,
3544
+ Drop: () => Drop,
3545
+ Editable: () => Editable,
3546
+ FocusEvents: () => FocusEvents,
3547
+ Keymap: () => Keymap,
3548
+ Paste: () => Paste,
3549
+ Tabindex: () => Tabindex,
3550
+ TextDirection: () => TextDirection,
3551
+ focusEventsPluginKey: () => focusEventsPluginKey
3552
+ });
3553
+ var Extension = class _Extension extends Extendable {
3554
+ constructor() {
3555
+ super(...arguments);
3556
+ this.type = "extension";
3557
+ }
3558
+ /**
3559
+ * Create a new Extension instance
3560
+ * @param config - Extension configuration object or a function that returns a configuration object
3561
+ */
3562
+ static create(config = {}) {
3563
+ const resolvedConfig = typeof config === "function" ? config() : config;
3564
+ return new _Extension(resolvedConfig);
3565
+ }
3566
+ configure(options) {
3567
+ return super.configure(options);
3568
+ }
3569
+ extend(extendedConfig) {
3570
+ const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
3571
+ return super.extend(resolvedConfig);
3572
+ }
3573
+ };
3574
+ var ClipboardTextSerializer = Extension.create({
3575
+ name: "clipboardTextSerializer",
3576
+ addOptions() {
3577
+ return {
3578
+ blockSeparator: void 0
3579
+ };
3580
+ },
3581
+ addProseMirrorPlugins() {
3582
+ return [
3583
+ new state.Plugin({
3584
+ key: new state.PluginKey("clipboardTextSerializer"),
3585
+ props: {
3586
+ clipboardTextSerializer: () => {
3587
+ const { editor } = this;
3588
+ const { state, schema } = editor;
3589
+ const { doc, selection } = state;
3590
+ const textSerializers = getTextSerializersFromSchema(schema);
3591
+ const { blockSeparator } = this.options;
3592
+ const options = {
3593
+ ...blockSeparator !== void 0 ? { blockSeparator } : {},
3594
+ textSerializers
3595
+ };
3596
+ const sortedRanges = [...selection.ranges].sort((a, b) => a.$from.pos - b.$from.pos);
3597
+ return sortedRanges.map(
3598
+ ({ $from, $to }) => getTextBetween(doc, { from: $from.pos, to: $to.pos }, options)
3599
+ ).join(blockSeparator != null ? blockSeparator : "\n\n");
3600
+ }
3601
+ }
3602
+ })
3603
+ ];
3604
+ }
3605
+ });
3606
+ var Commands = Extension.create({
3607
+ name: "commands",
3608
+ addCommands() {
3609
+ return {
3610
+ ...commands_exports
3611
+ };
3612
+ }
3613
+ });
3614
+ var Delete = Extension.create({
3615
+ name: "delete",
3616
+ onUpdate({ transaction, appendedTransactions }) {
3617
+ var _a, _b, _c;
3618
+ const callback = () => {
3619
+ var _a2, _b2, _c2, _d;
3620
+ if ((_d = (_c2 = (_b2 = (_a2 = this.editor.options.coreExtensionOptions) == null ? void 0 : _a2.delete) == null ? void 0 : _b2.filterTransaction) == null ? void 0 : _c2.call(_b2, transaction)) != null ? _d : transaction.getMeta("y-sync$")) {
3621
+ return;
3622
+ }
3623
+ const nextTransaction = combineTransactionSteps(transaction.before, [
3624
+ transaction,
3625
+ ...appendedTransactions
3626
+ ]);
3627
+ const changes = getChangedRanges(nextTransaction);
3628
+ changes.forEach((change) => {
3629
+ if (nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter && nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore) {
3630
+ nextTransaction.before.nodesBetween(
3631
+ change.oldRange.from,
3632
+ change.oldRange.to,
3633
+ (node, from) => {
3634
+ const to = from + node.nodeSize - 2;
3635
+ const isFullyWithinRange = change.oldRange.from <= from && to <= change.oldRange.to;
3636
+ this.editor.emit("delete", {
3637
+ type: "node",
3638
+ node,
3639
+ from,
3640
+ to,
3641
+ newFrom: nextTransaction.mapping.map(from),
3642
+ newTo: nextTransaction.mapping.map(to),
3643
+ deletedRange: change.oldRange,
3644
+ newRange: change.newRange,
3645
+ partial: !isFullyWithinRange,
3646
+ editor: this.editor,
3647
+ transaction,
3648
+ combinedTransform: nextTransaction
3649
+ });
3650
+ }
3651
+ );
3652
+ }
3653
+ });
3654
+ const mapping = nextTransaction.mapping;
3655
+ nextTransaction.steps.forEach((step, index) => {
3656
+ var _a3, _b3;
3657
+ if (step instanceof transform.RemoveMarkStep) {
3658
+ const newStart = mapping.slice(index).map(step.from, -1);
3659
+ const newEnd = mapping.slice(index).map(step.to);
3660
+ const oldStart = mapping.invert().map(newStart, -1);
3661
+ const oldEnd = mapping.invert().map(newEnd);
3662
+ const foundBeforeMark = newStart > 0 ? (_a3 = nextTransaction.doc.nodeAt(newStart - 1)) == null ? void 0 : _a3.marks.some((mark) => mark.eq(step.mark)) : false;
3663
+ const foundAfterMark = (_b3 = nextTransaction.doc.nodeAt(newEnd)) == null ? void 0 : _b3.marks.some((mark) => mark.eq(step.mark));
3664
+ this.editor.emit("delete", {
3665
+ type: "mark",
3666
+ mark: step.mark,
3667
+ from: step.from,
3668
+ to: step.to,
3669
+ deletedRange: {
3670
+ from: oldStart,
3671
+ to: oldEnd
3672
+ },
3673
+ newRange: {
3674
+ from: newStart,
3675
+ to: newEnd
3676
+ },
3677
+ partial: Boolean(foundAfterMark || foundBeforeMark),
3678
+ editor: this.editor,
3679
+ transaction,
3680
+ combinedTransform: nextTransaction
3681
+ });
3682
+ }
3683
+ });
3684
+ };
3685
+ if ((_c = (_b = (_a = this.editor.options.coreExtensionOptions) == null ? void 0 : _a.delete) == null ? void 0 : _b.async) != null ? _c : true) {
3686
+ setTimeout(callback, 0);
3687
+ } else {
3688
+ callback();
3689
+ }
3690
+ }
3691
+ });
3692
+ var Drop = Extension.create({
3693
+ name: "drop",
3694
+ addProseMirrorPlugins() {
3695
+ return [
3696
+ new state.Plugin({
3697
+ key: new state.PluginKey("tiptapDrop"),
3698
+ props: {
3699
+ handleDrop: (_, e, slice, moved) => {
3700
+ this.editor.emit("drop", {
3701
+ editor: this.editor,
3702
+ event: e,
3703
+ slice,
3704
+ moved
3705
+ });
3706
+ }
3707
+ }
3708
+ })
3709
+ ];
3710
+ }
3711
+ });
3712
+ var Editable = Extension.create({
3713
+ name: "editable",
3714
+ addProseMirrorPlugins() {
3715
+ return [
3716
+ new state.Plugin({
3717
+ key: new state.PluginKey("editable"),
3718
+ props: {
3719
+ editable: () => this.editor.options.editable
3720
+ }
3721
+ })
3722
+ ];
3723
+ }
3724
+ });
3725
+ var focusEventsPluginKey = new state.PluginKey("focusEvents");
3726
+ var FocusEvents = Extension.create({
3727
+ name: "focusEvents",
3728
+ addProseMirrorPlugins() {
3729
+ const { editor } = this;
3730
+ return [
3731
+ new state.Plugin({
3732
+ key: focusEventsPluginKey,
3733
+ props: {
3734
+ handleDOMEvents: {
3735
+ focus: (view, event) => {
3736
+ editor.isFocused = true;
3737
+ const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false);
3738
+ view.dispatch(transaction);
3739
+ return false;
3740
+ },
3741
+ blur: (view, event) => {
3742
+ editor.isFocused = false;
3743
+ const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false);
3744
+ view.dispatch(transaction);
3745
+ return false;
3746
+ }
3747
+ }
3748
+ }
3749
+ })
3750
+ ];
3751
+ }
3752
+ });
3753
+ var Keymap = Extension.create({
3754
+ name: "keymap",
3755
+ addKeyboardShortcuts() {
3756
+ const handleBackspace = () => this.editor.commands.first(({ commands }) => [
3757
+ () => commands.undoInputRule(),
3758
+ // maybe convert first text block node to default node
3759
+ () => commands.command(({ tr }) => {
3760
+ const { selection, doc } = tr;
3761
+ const { empty, $anchor } = selection;
3762
+ const { pos, parent } = $anchor;
3763
+ const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr.doc.resolve(pos - 1) : $anchor;
3764
+ const parentIsIsolating = $parentPos.parent.type.spec.isolating;
3765
+ const parentPos = $anchor.pos - $anchor.parentOffset;
3766
+ const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : state.Selection.atStart(doc).from === pos;
3767
+ if (!empty || !parent.type.isTextblock || parent.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") {
3768
+ return false;
3769
+ }
3770
+ return commands.clearNodes();
3771
+ }),
3772
+ () => commands.deleteSelection(),
3773
+ () => commands.joinBackward(),
3774
+ () => commands.selectNodeBackward()
3775
+ ]);
3776
+ const handleDelete = () => this.editor.commands.first(({ commands }) => [
3777
+ () => commands.deleteSelection(),
3778
+ () => commands.deleteCurrentNode(),
3779
+ () => commands.joinForward(),
3780
+ () => commands.selectNodeForward()
3781
+ ]);
3782
+ const handleEnter = () => this.editor.commands.first(({ commands }) => [
3783
+ () => commands.newlineInCode(),
3784
+ () => commands.createParagraphNear(),
3785
+ () => commands.liftEmptyBlock(),
3786
+ () => commands.splitBlock()
3787
+ ]);
3788
+ const baseKeymap = {
3789
+ Enter: handleEnter,
3790
+ "Mod-Enter": () => this.editor.commands.exitCode(),
3791
+ Backspace: handleBackspace,
3792
+ "Mod-Backspace": handleBackspace,
3793
+ "Shift-Backspace": handleBackspace,
3794
+ Delete: handleDelete,
3795
+ "Mod-Delete": handleDelete,
3796
+ "Mod-a": () => this.editor.commands.selectAll()
3797
+ };
3798
+ const pcKeymap = {
3799
+ ...baseKeymap
3800
+ };
3801
+ const macKeymap = {
3802
+ ...baseKeymap,
3803
+ "Ctrl-h": handleBackspace,
3804
+ "Alt-Backspace": handleBackspace,
3805
+ "Ctrl-d": handleDelete,
3806
+ "Ctrl-Alt-Backspace": handleDelete,
3807
+ "Alt-Delete": handleDelete,
3808
+ "Alt-d": handleDelete,
3809
+ "Ctrl-a": () => this.editor.commands.selectTextblockStart(),
3810
+ "Ctrl-e": () => this.editor.commands.selectTextblockEnd()
3811
+ };
3812
+ if (isiOS() || isMacOS()) {
3813
+ return macKeymap;
3814
+ }
3815
+ return pcKeymap;
3816
+ },
3817
+ addProseMirrorPlugins() {
3818
+ return [
3819
+ // With this plugin we check if the whole document was selected and deleted.
3820
+ // In this case we will additionally call `clearNodes()` to convert e.g. a heading
3821
+ // to a paragraph if necessary.
3822
+ // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well
3823
+ // with many other commands.
3824
+ new state.Plugin({
3825
+ key: new state.PluginKey("clearDocument"),
3826
+ appendTransaction: (transactions, oldState, newState) => {
3827
+ if (transactions.some((tr2) => tr2.getMeta("composition"))) {
3828
+ return;
3829
+ }
3830
+ const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc);
3831
+ const ignoreTr = transactions.some(
3832
+ (transaction) => transaction.getMeta("preventClearDocument")
3833
+ );
3834
+ if (!docChanges || ignoreTr) {
3835
+ return;
3836
+ }
3837
+ const { empty, from, to } = oldState.selection;
3838
+ const allFrom = state.Selection.atStart(oldState.doc).from;
3839
+ const allEnd = state.Selection.atEnd(oldState.doc).to;
3840
+ const allWasSelected = from === allFrom && to === allEnd;
3841
+ if (empty || !allWasSelected) {
3842
+ return;
3843
+ }
3844
+ const isEmpty = isNodeEmpty(newState.doc);
3845
+ if (!isEmpty) {
3846
+ return;
3847
+ }
3848
+ const tr = newState.tr;
3849
+ const state$1 = createChainableState({
3850
+ state: newState,
3851
+ transaction: tr
3852
+ });
3853
+ const { commands } = new CommandManager({
3854
+ editor: this.editor,
3855
+ state: state$1
3856
+ });
3857
+ commands.clearNodes();
3858
+ if (!tr.steps.length) {
3859
+ return;
3860
+ }
3861
+ return tr;
3862
+ }
3863
+ })
3864
+ ];
3865
+ }
3866
+ });
3867
+ var Paste = Extension.create({
3868
+ name: "paste",
3869
+ addProseMirrorPlugins() {
3870
+ return [
3871
+ new state.Plugin({
3872
+ key: new state.PluginKey("tiptapPaste"),
3873
+ props: {
3874
+ handlePaste: (_view, e, slice) => {
3875
+ this.editor.emit("paste", {
3876
+ editor: this.editor,
3877
+ event: e,
3878
+ slice
3879
+ });
3880
+ }
3881
+ }
3882
+ })
3883
+ ];
3884
+ }
3885
+ });
3886
+ var Tabindex = Extension.create({
3887
+ name: "tabindex",
3888
+ addOptions() {
3889
+ return {
3890
+ value: void 0
3891
+ };
3892
+ },
3893
+ addProseMirrorPlugins() {
3894
+ return [
3895
+ new state.Plugin({
3896
+ key: new state.PluginKey("tabindex"),
3897
+ props: {
3898
+ attributes: () => {
3899
+ var _a;
3900
+ if (!this.editor.isEditable && this.options.value === void 0) {
3901
+ return {};
3902
+ }
3903
+ return { tabindex: (_a = this.options.value) != null ? _a : "0" };
3904
+ }
3905
+ }
3906
+ })
3907
+ ];
3908
+ }
3909
+ });
3910
+ var TextDirection = Extension.create({
3911
+ name: "textDirection",
3912
+ addOptions() {
3913
+ return {
3914
+ direction: void 0
3915
+ };
3916
+ },
3917
+ addGlobalAttributes() {
3918
+ if (!this.options.direction) {
3919
+ return [];
3920
+ }
3921
+ const { nodeExtensions } = splitExtensions(this.extensions);
3922
+ return [
3923
+ {
3924
+ types: nodeExtensions.filter((extension) => extension.name !== "text").map((extension) => extension.name),
3925
+ attributes: {
3926
+ dir: {
3927
+ default: this.options.direction,
3928
+ parseHTML: (element) => {
3929
+ const dir = element.getAttribute("dir");
3930
+ if (dir && (dir === "ltr" || dir === "rtl" || dir === "auto")) {
3931
+ return dir;
3932
+ }
3933
+ return this.options.direction;
3934
+ },
3935
+ renderHTML: (attributes) => {
3936
+ if (!attributes.dir) {
3937
+ return {};
3938
+ }
3939
+ return {
3940
+ dir: attributes.dir
3941
+ };
3942
+ }
3943
+ }
3944
+ }
3945
+ }
3946
+ ];
3947
+ },
3948
+ addProseMirrorPlugins() {
3949
+ return [
3950
+ new state.Plugin({
3951
+ key: new state.PluginKey("textDirection"),
3952
+ props: {
3953
+ attributes: () => {
3954
+ const direction = this.options.direction;
3955
+ if (!direction) {
3956
+ return {};
3957
+ }
3958
+ return {
3959
+ dir: direction
3960
+ };
3961
+ }
3962
+ }
3963
+ })
3964
+ ];
3965
+ }
3966
+ });
3967
+ var markdown_exports = {};
3968
+ __export(markdown_exports, {
3969
+ createAtomBlockMarkdownSpec: () => createAtomBlockMarkdownSpec,
3970
+ createBlockMarkdownSpec: () => createBlockMarkdownSpec,
3971
+ createInlineMarkdownSpec: () => createInlineMarkdownSpec,
3972
+ parseAttributes: () => parseAttributes,
3973
+ parseIndentedBlocks: () => parseIndentedBlocks,
3974
+ renderNestedMarkdownContent: () => renderNestedMarkdownContent,
3975
+ serializeAttributes: () => serializeAttributes
3976
+ });
3977
+ function parseAttributes(attrString) {
3978
+ if (!(attrString == null ? void 0 : attrString.trim())) {
3979
+ return {};
3980
+ }
3981
+ const attributes = {};
3982
+ const quotedStrings = [];
3983
+ const tempString = attrString.replace(/["']([^"']*)["']/g, (match) => {
3984
+ quotedStrings.push(match);
3985
+ return `__QUOTED_${quotedStrings.length - 1}__`;
3986
+ });
3987
+ const classMatches = tempString.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);
3988
+ if (classMatches) {
3989
+ const classes = classMatches.map((match) => match.trim().slice(1));
3990
+ attributes.class = classes.join(" ");
3991
+ }
3992
+ const idMatch = tempString.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);
3993
+ if (idMatch) {
3994
+ attributes.id = idMatch[1];
3995
+ }
3996
+ const kvRegex = /([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;
3997
+ const kvMatches = Array.from(tempString.matchAll(kvRegex));
3998
+ kvMatches.forEach(([, key, quotedRef]) => {
3999
+ var _a;
4000
+ const quotedIndex = parseInt(((_a = quotedRef.match(/__QUOTED_(\d+)__/)) == null ? void 0 : _a[1]) || "0", 10);
4001
+ const quotedValue = quotedStrings[quotedIndex];
4002
+ if (quotedValue) {
4003
+ attributes[key] = quotedValue.slice(1, -1);
4004
+ }
4005
+ });
4006
+ const cleanString = tempString.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g, "").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g, "").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g, "").trim();
4007
+ if (cleanString) {
4008
+ const booleanAttrs = cleanString.split(/\s+/).filter(Boolean);
4009
+ booleanAttrs.forEach((attr) => {
4010
+ if (attr.match(/^[a-zA-Z][\w-]*$/)) {
4011
+ attributes[attr] = true;
4012
+ }
4013
+ });
4014
+ }
4015
+ return attributes;
4016
+ }
4017
+ function serializeAttributes(attributes) {
4018
+ if (!attributes || Object.keys(attributes).length === 0) {
4019
+ return "";
4020
+ }
4021
+ const parts = [];
4022
+ if (attributes.class) {
4023
+ const classes = String(attributes.class).split(/\s+/).filter(Boolean);
4024
+ classes.forEach((cls) => parts.push(`.${cls}`));
4025
+ }
4026
+ if (attributes.id) {
4027
+ parts.push(`#${attributes.id}`);
4028
+ }
4029
+ Object.entries(attributes).forEach(([key, value]) => {
4030
+ if (key === "class" || key === "id") {
4031
+ return;
4032
+ }
4033
+ if (value === true) {
4034
+ parts.push(key);
4035
+ } else if (value !== false && value != null) {
4036
+ parts.push(`${key}="${String(value)}"`);
4037
+ }
4038
+ });
4039
+ return parts.join(" ");
4040
+ }
4041
+ function createAtomBlockMarkdownSpec(options) {
4042
+ const {
4043
+ nodeName,
4044
+ name: markdownName,
4045
+ parseAttributes: parseAttributes2 = parseAttributes,
4046
+ serializeAttributes: serializeAttributes2 = serializeAttributes,
4047
+ defaultAttributes = {},
4048
+ requiredAttributes = [],
4049
+ allowedAttributes
4050
+ } = options;
4051
+ const blockName = markdownName || nodeName;
4052
+ const filterAttributes = (attrs) => {
4053
+ if (!allowedAttributes) {
4054
+ return attrs;
4055
+ }
4056
+ const filtered = {};
4057
+ allowedAttributes.forEach((key) => {
4058
+ if (key in attrs) {
4059
+ filtered[key] = attrs[key];
4060
+ }
4061
+ });
4062
+ return filtered;
4063
+ };
4064
+ return {
4065
+ parseMarkdown: (token, h2) => {
4066
+ const attrs = { ...defaultAttributes, ...token.attributes };
4067
+ return h2.createNode(nodeName, attrs, []);
4068
+ },
4069
+ markdownTokenizer: {
4070
+ name: nodeName,
4071
+ level: "block",
4072
+ start(src) {
4073
+ var _a;
4074
+ const regex = new RegExp(`^:::${blockName}(?:\\s|$)`, "m");
4075
+ const index = (_a = src.match(regex)) == null ? void 0 : _a.index;
4076
+ return index !== void 0 ? index : -1;
4077
+ },
4078
+ tokenize(src, _tokens, _lexer) {
4079
+ const regex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`);
4080
+ const match = src.match(regex);
4081
+ if (!match) {
4082
+ return void 0;
4083
+ }
4084
+ const attrString = match[1] || "";
4085
+ const attributes = parseAttributes2(attrString);
4086
+ const missingRequired = requiredAttributes.find((required) => !(required in attributes));
4087
+ if (missingRequired) {
4088
+ return void 0;
4089
+ }
4090
+ return {
4091
+ type: nodeName,
4092
+ raw: match[0],
4093
+ attributes
4094
+ };
4095
+ }
4096
+ },
4097
+ renderMarkdown: (node) => {
4098
+ const filteredAttrs = filterAttributes(node.attrs || {});
4099
+ const attrs = serializeAttributes2(filteredAttrs);
4100
+ const attrString = attrs ? ` {${attrs}}` : "";
4101
+ return `:::${blockName}${attrString} :::`;
4102
+ }
4103
+ };
4104
+ }
4105
+ function createBlockMarkdownSpec(options) {
4106
+ const {
4107
+ nodeName,
4108
+ name: markdownName,
4109
+ getContent,
4110
+ parseAttributes: parseAttributes2 = parseAttributes,
4111
+ serializeAttributes: serializeAttributes2 = serializeAttributes,
4112
+ defaultAttributes = {},
4113
+ content = "block",
4114
+ allowedAttributes
4115
+ } = options;
4116
+ const blockName = markdownName || nodeName;
4117
+ const filterAttributes = (attrs) => {
4118
+ if (!allowedAttributes) {
4119
+ return attrs;
4120
+ }
4121
+ const filtered = {};
4122
+ allowedAttributes.forEach((key) => {
4123
+ if (key in attrs) {
4124
+ filtered[key] = attrs[key];
4125
+ }
4126
+ });
4127
+ return filtered;
4128
+ };
4129
+ return {
4130
+ parseMarkdown: (token, h2) => {
4131
+ let nodeContent;
4132
+ if (getContent) {
4133
+ const contentResult = getContent(token);
4134
+ nodeContent = typeof contentResult === "string" ? [{ type: "text", text: contentResult }] : contentResult;
4135
+ } else if (content === "block") {
4136
+ nodeContent = h2.parseChildren(token.tokens || []);
4137
+ } else {
4138
+ nodeContent = h2.parseInline(token.tokens || []);
4139
+ }
4140
+ const attrs = { ...defaultAttributes, ...token.attributes };
4141
+ return h2.createNode(nodeName, attrs, nodeContent);
4142
+ },
4143
+ markdownTokenizer: {
4144
+ name: nodeName,
4145
+ level: "block",
4146
+ start(src) {
4147
+ var _a;
4148
+ const regex = new RegExp(`^:::${blockName}`, "m");
4149
+ const index = (_a = src.match(regex)) == null ? void 0 : _a.index;
4150
+ return index !== void 0 ? index : -1;
4151
+ },
4152
+ tokenize(src, _tokens, lexer) {
4153
+ var _a;
4154
+ const openingRegex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*\\n`);
4155
+ const openingMatch = src.match(openingRegex);
4156
+ if (!openingMatch) {
4157
+ return void 0;
4158
+ }
4159
+ const [openingTag, attrString = ""] = openingMatch;
4160
+ const attributes = parseAttributes2(attrString);
4161
+ let level = 1;
4162
+ const position = openingTag.length;
4163
+ let matchedContent = "";
4164
+ const blockPattern = /^:::([\w-]*)(\s.*)?/gm;
4165
+ const remaining = src.slice(position);
4166
+ blockPattern.lastIndex = 0;
4167
+ for (; ; ) {
4168
+ const match = blockPattern.exec(remaining);
4169
+ if (match === null) {
4170
+ break;
4171
+ }
4172
+ const matchPos = match.index;
4173
+ const blockType = match[1];
4174
+ if ((_a = match[2]) == null ? void 0 : _a.endsWith(":::")) {
4175
+ continue;
4176
+ }
4177
+ if (blockType) {
4178
+ level += 1;
4179
+ } else {
4180
+ level -= 1;
4181
+ if (level === 0) {
4182
+ const rawContent = remaining.slice(0, matchPos);
4183
+ matchedContent = rawContent.trim();
4184
+ const fullMatch = src.slice(0, position + matchPos + match[0].length);
4185
+ let contentTokens = [];
4186
+ if (matchedContent) {
4187
+ if (content === "block") {
4188
+ contentTokens = lexer.blockTokens(rawContent);
4189
+ contentTokens.forEach((token) => {
4190
+ if (token.text && (!token.tokens || token.tokens.length === 0)) {
4191
+ token.tokens = lexer.inlineTokens(token.text);
4192
+ }
4193
+ });
4194
+ while (contentTokens.length > 0) {
4195
+ const lastToken = contentTokens[contentTokens.length - 1];
4196
+ if (lastToken.type === "paragraph" && (!lastToken.text || lastToken.text.trim() === "")) {
4197
+ contentTokens.pop();
4198
+ } else {
4199
+ break;
4200
+ }
4201
+ }
4202
+ } else {
4203
+ contentTokens = lexer.inlineTokens(matchedContent);
4204
+ }
4205
+ }
4206
+ return {
4207
+ type: nodeName,
4208
+ raw: fullMatch,
4209
+ attributes,
4210
+ content: matchedContent,
4211
+ tokens: contentTokens
4212
+ };
4213
+ }
4214
+ }
4215
+ }
4216
+ return void 0;
4217
+ }
4218
+ },
4219
+ renderMarkdown: (node, h2) => {
4220
+ const filteredAttrs = filterAttributes(node.attrs || {});
4221
+ const attrs = serializeAttributes2(filteredAttrs);
4222
+ const attrString = attrs ? ` {${attrs}}` : "";
4223
+ const renderedContent = h2.renderChildren(node.content || [], "\n\n");
4224
+ return `:::${blockName}${attrString}
4225
+
4226
+ ${renderedContent}
4227
+
4228
+ :::`;
4229
+ }
4230
+ };
4231
+ }
4232
+ function parseShortcodeAttributes(attrString) {
4233
+ if (!attrString.trim()) {
4234
+ return {};
4235
+ }
4236
+ const attributes = {};
4237
+ const regex = /(\w+)=(?:"([^"]*)"|'([^']*)')/g;
4238
+ let match = regex.exec(attrString);
4239
+ while (match !== null) {
4240
+ const [, key, doubleQuoted, singleQuoted] = match;
4241
+ attributes[key] = doubleQuoted || singleQuoted;
4242
+ match = regex.exec(attrString);
4243
+ }
4244
+ return attributes;
4245
+ }
4246
+ function serializeShortcodeAttributes(attrs) {
4247
+ return Object.entries(attrs).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => `${key}="${value}"`).join(" ");
4248
+ }
4249
+ function createInlineMarkdownSpec(options) {
4250
+ const {
4251
+ nodeName,
4252
+ name: shortcodeName,
4253
+ getContent,
4254
+ parseAttributes: parseAttributes2 = parseShortcodeAttributes,
4255
+ serializeAttributes: serializeAttributes2 = serializeShortcodeAttributes,
4256
+ defaultAttributes = {},
4257
+ selfClosing = false,
4258
+ allowedAttributes
4259
+ } = options;
4260
+ const shortcode = shortcodeName || nodeName;
4261
+ const filterAttributes = (attrs) => {
4262
+ if (!allowedAttributes) {
4263
+ return attrs;
4264
+ }
4265
+ const filtered = {};
4266
+ allowedAttributes.forEach((attr) => {
4267
+ const attrName = typeof attr === "string" ? attr : attr.name;
4268
+ const skipIfDefault = typeof attr === "string" ? void 0 : attr.skipIfDefault;
4269
+ if (attrName in attrs) {
4270
+ const value = attrs[attrName];
4271
+ if (skipIfDefault !== void 0 && value === skipIfDefault) {
4272
+ return;
4273
+ }
4274
+ filtered[attrName] = value;
4275
+ }
4276
+ });
4277
+ return filtered;
4278
+ };
4279
+ const escapedShortcode = shortcode.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4280
+ return {
4281
+ parseMarkdown: (token, h2) => {
4282
+ const attrs = { ...defaultAttributes, ...token.attributes };
4283
+ if (selfClosing) {
4284
+ return h2.createNode(nodeName, attrs);
4285
+ }
4286
+ const content = getContent ? getContent(token) : token.content || "";
4287
+ if (content) {
4288
+ return h2.createNode(nodeName, attrs, [h2.createTextNode(content)]);
4289
+ }
4290
+ return h2.createNode(nodeName, attrs, []);
4291
+ },
4292
+ markdownTokenizer: {
4293
+ name: nodeName,
4294
+ level: "inline",
4295
+ start(src) {
4296
+ const startPattern = selfClosing ? new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\]`) : new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${escapedShortcode}\\]`);
4297
+ const match = src.match(startPattern);
4298
+ const index = match == null ? void 0 : match.index;
4299
+ return index !== void 0 ? index : -1;
4300
+ },
4301
+ tokenize(src, _tokens, _lexer) {
4302
+ const tokenPattern = selfClosing ? new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]`) : new RegExp(
4303
+ `^\\[${escapedShortcode}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${escapedShortcode}\\]`
4304
+ );
4305
+ const match = src.match(tokenPattern);
4306
+ if (!match) {
4307
+ return void 0;
4308
+ }
4309
+ let content = "";
4310
+ let attrString = "";
4311
+ if (selfClosing) {
4312
+ const [, attrs] = match;
4313
+ attrString = attrs;
4314
+ } else {
4315
+ const [, attrs, contentMatch] = match;
4316
+ attrString = attrs;
4317
+ content = contentMatch || "";
4318
+ }
4319
+ const attributes = parseAttributes2(attrString.trim());
4320
+ return {
4321
+ type: nodeName,
4322
+ raw: match[0],
4323
+ content: content.trim(),
4324
+ attributes
4325
+ };
4326
+ }
4327
+ },
4328
+ renderMarkdown: (node) => {
4329
+ let content = "";
4330
+ if (getContent) {
4331
+ content = getContent(node);
4332
+ } else if (node.content && node.content.length > 0) {
4333
+ content = node.content.filter((child) => child.type === "text").map((child) => child.text).join("");
4334
+ }
4335
+ const filteredAttrs = filterAttributes(node.attrs || {});
4336
+ const attrs = serializeAttributes2(filteredAttrs);
4337
+ const attrString = attrs ? ` ${attrs}` : "";
4338
+ if (selfClosing) {
4339
+ return `[${shortcode}${attrString}]`;
4340
+ }
4341
+ return `[${shortcode}${attrString}]${content}[/${shortcode}]`;
4342
+ }
4343
+ };
4344
+ }
4345
+ function parseIndentedBlocks(src, config, lexer) {
4346
+ var _a, _b, _c, _d;
4347
+ const lines = src.split("\n");
4348
+ const items = [];
4349
+ let totalRaw = "";
4350
+ let i = 0;
4351
+ const baseIndentSize = config.baseIndentSize || 2;
4352
+ while (i < lines.length) {
4353
+ const currentLine = lines[i];
4354
+ const itemMatch = currentLine.match(config.itemPattern);
4355
+ if (!itemMatch) {
4356
+ if (items.length > 0) {
4357
+ break;
4358
+ } else if (currentLine.trim() === "") {
4359
+ i += 1;
4360
+ totalRaw = `${totalRaw}${currentLine}
4361
+ `;
4362
+ continue;
4363
+ } else {
4364
+ return void 0;
4365
+ }
4366
+ }
4367
+ const itemData = config.extractItemData(itemMatch);
4368
+ const { indentLevel, mainContent } = itemData;
4369
+ totalRaw = `${totalRaw}${currentLine}
4370
+ `;
4371
+ const itemContent = [mainContent];
4372
+ i += 1;
4373
+ while (i < lines.length) {
4374
+ const nextLine = lines[i];
4375
+ if (nextLine.trim() === "") {
4376
+ const nextNonEmptyIndex = lines.slice(i + 1).findIndex((l) => l.trim() !== "");
4377
+ if (nextNonEmptyIndex === -1) {
4378
+ break;
4379
+ }
4380
+ const nextNonEmpty = lines[i + 1 + nextNonEmptyIndex];
4381
+ const nextIndent2 = ((_b = (_a = nextNonEmpty.match(/^(\s*)/)) == null ? void 0 : _a[1]) == null ? void 0 : _b.length) || 0;
4382
+ if (nextIndent2 > indentLevel) {
4383
+ itemContent.push(nextLine);
4384
+ totalRaw = `${totalRaw}${nextLine}
4385
+ `;
4386
+ i += 1;
4387
+ continue;
4388
+ } else {
4389
+ break;
4390
+ }
4391
+ }
4392
+ const nextIndent = ((_d = (_c = nextLine.match(/^(\s*)/)) == null ? void 0 : _c[1]) == null ? void 0 : _d.length) || 0;
4393
+ if (nextIndent > indentLevel) {
4394
+ itemContent.push(nextLine);
4395
+ totalRaw = `${totalRaw}${nextLine}
4396
+ `;
4397
+ i += 1;
4398
+ } else {
4399
+ break;
4400
+ }
4401
+ }
4402
+ let nestedTokens;
4403
+ const nestedContent = itemContent.slice(1);
4404
+ if (nestedContent.length > 0) {
4405
+ const dedentedNested = nestedContent.map((nestedLine) => nestedLine.slice(indentLevel + baseIndentSize)).join("\n");
4406
+ if (dedentedNested.trim()) {
4407
+ if (config.customNestedParser) {
4408
+ nestedTokens = config.customNestedParser(dedentedNested);
4409
+ } else {
4410
+ nestedTokens = lexer.blockTokens(dedentedNested);
4411
+ }
4412
+ }
4413
+ }
4414
+ const token = config.createToken(itemData, nestedTokens);
4415
+ items.push(token);
4416
+ }
4417
+ if (items.length === 0) {
4418
+ return void 0;
4419
+ }
4420
+ return {
4421
+ items,
4422
+ raw: totalRaw
4423
+ };
4424
+ }
4425
+ function renderNestedMarkdownContent(node, h2, prefixOrGenerator, ctx) {
4426
+ if (!node || !Array.isArray(node.content)) {
4427
+ return "";
4428
+ }
4429
+ const prefix = typeof prefixOrGenerator === "function" ? prefixOrGenerator(ctx) : prefixOrGenerator;
4430
+ const [content, ...children] = node.content;
4431
+ const mainContent = h2.renderChildren([content]);
4432
+ let output = `${prefix}${mainContent}`;
4433
+ if (children && children.length > 0) {
4434
+ children.forEach((child, index) => {
4435
+ var _a, _b;
4436
+ const childContent = (_b = (_a = h2.renderChild) == null ? void 0 : _a.call(h2, child, index + 1)) != null ? _b : h2.renderChildren([child]);
4437
+ if (childContent !== void 0 && childContent !== null) {
4438
+ const indentedChild = childContent.split("\n").map((line) => line ? h2.indent(line) : h2.indent("")).join("\n");
4439
+ output += child.type === "paragraph" ? `
4440
+
4441
+ ${indentedChild}` : `
4442
+ ${indentedChild}`;
4443
+ }
4444
+ });
4445
+ }
4446
+ return output;
4447
+ }
4448
+ var Node3 = class _Node extends Extendable {
4449
+ constructor() {
4450
+ super(...arguments);
4451
+ this.type = "node";
4452
+ }
4453
+ /**
4454
+ * Create a new Node instance
4455
+ * @param config - Node configuration object or a function that returns a configuration object
4456
+ */
4457
+ static create(config = {}) {
4458
+ const resolvedConfig = typeof config === "function" ? config() : config;
4459
+ return new _Node(resolvedConfig);
4460
+ }
4461
+ configure(options) {
4462
+ return super.configure(options);
4463
+ }
4464
+ extend(extendedConfig) {
4465
+ const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
4466
+ return super.extend(resolvedConfig);
4467
+ }
4468
+ };
4469
+
4470
+ // src/components/RichTextEditor/extensions/Highlight.ts
4471
+ var Highlight = Mark.create({
4472
+ name: "highlight",
4473
+ renderHTML({ HTMLAttributes }) {
4474
+ return ["mark", { style: "background: #fef08a; border-radius: 2px; padding: 0 2px;", ...HTMLAttributes }, 0];
4475
+ },
4476
+ parseHTML() {
4477
+ return [{ tag: "mark" }];
4478
+ },
4479
+ addKeyboardShortcuts() {
4480
+ return {
4481
+ "Mod-Shift-h": () => this.editor.commands.toggleMark(this.name)
4482
+ };
4483
+ }
4484
+ });
4485
+ var HighlightIcon = () => /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": "true", children: [
4486
+ /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "1", y: "8", width: "12", height: "3", rx: "1", fill: "#fef08a", stroke: "currentColor", strokeWidth: "1" }),
4487
+ /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M4 8L5.5 3h3L10 8", stroke: "currentColor", strokeWidth: "1.2", strokeLinecap: "round", strokeLinejoin: "round" }),
4488
+ /* @__PURE__ */ jsxRuntime.jsx("line", { x1: "4.5", y1: "6", x2: "9.5", y2: "6", stroke: "currentColor", strokeWidth: "1", strokeLinecap: "round" })
4489
+ ] });
4490
+ var HighlightButton = () => {
4491
+ const { editor } = react.useCurrentEditor();
4492
+ if (!editor) return null;
4493
+ const active = editor.isActive("highlight");
4494
+ return /* @__PURE__ */ jsxRuntime.jsx(
4495
+ "button",
4496
+ {
4497
+ type: "button",
4498
+ title: "Highlight (Mod+Shift+H)",
4499
+ "aria-label": "Highlight",
4500
+ "aria-pressed": active,
4501
+ className: [RichTextEditor_module_default.toolbarButton, active ? RichTextEditor_module_default.active : ""].filter(Boolean).join(" "),
4502
+ onMouseDown: (e) => {
4503
+ e.preventDefault();
4504
+ editor.chain().focus().toggleMark("highlight").run();
4505
+ },
4506
+ children: /* @__PURE__ */ jsxRuntime.jsx(HighlightIcon, {})
4507
+ }
4508
+ );
4509
+ };
4510
+
4511
+ // src/components/RichTextEditor/extensions/PageBreak.ts
4512
+ var PageBreak = Node3.create({
4513
+ name: "pageBreak",
4514
+ group: "block",
4515
+ atom: true,
4516
+ parseHTML() {
4517
+ return [{ tag: 'div[data-type="page-break"]' }];
4518
+ },
4519
+ renderHTML({ HTMLAttributes }) {
4520
+ return ["div", mergeAttributes(HTMLAttributes, { "data-type": "page-break" })];
4521
+ },
4522
+ addKeyboardShortcuts() {
4523
+ return {
4524
+ "Mod-Enter": () => this.editor.commands.insertContent({ type: this.name })
4525
+ };
4526
+ }
4527
+ });
4528
+ var PageBreakIcon = () => /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
4529
+ /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "3", y: "1", width: "10", height: "6", rx: "1", stroke: "currentColor", strokeWidth: "1.2" }),
4530
+ /* @__PURE__ */ jsxRuntime.jsx("rect", { x: "3", y: "9", width: "10", height: "6", rx: "1", stroke: "currentColor", strokeWidth: "1.2" }),
4531
+ /* @__PURE__ */ jsxRuntime.jsx("line", { x1: "1", y1: "8", x2: "5", y2: "8", stroke: "currentColor", strokeWidth: "1.2", strokeLinecap: "round", strokeDasharray: "1.5 1.5" }),
4532
+ /* @__PURE__ */ jsxRuntime.jsx("line", { x1: "7", y1: "8", x2: "9", y2: "8", stroke: "currentColor", strokeWidth: "1.2", strokeLinecap: "round", strokeDasharray: "1.5 1.5" }),
4533
+ /* @__PURE__ */ jsxRuntime.jsx("line", { x1: "11", y1: "8", x2: "15", y2: "8", stroke: "currentColor", strokeWidth: "1.2", strokeLinecap: "round", strokeDasharray: "1.5 1.5" })
4534
+ ] });
4535
+ var PageBreakButton = () => {
4536
+ const { editor } = react.useCurrentEditor();
4537
+ if (!editor) return null;
4538
+ return /* @__PURE__ */ jsxRuntime.jsx(
4539
+ "button",
4540
+ {
4541
+ type: "button",
4542
+ title: "Page break (Mod+Enter)",
4543
+ "aria-label": "Insert page break",
4544
+ className: RichTextEditor_module_default.toolbarButton,
4545
+ onMouseDown: (e) => {
4546
+ e.preventDefault();
4547
+ editor.chain().focus().insertContent({ type: "pageBreak" }).run();
4548
+ },
4549
+ children: /* @__PURE__ */ jsxRuntime.jsx(PageBreakIcon, {})
4550
+ }
4551
+ );
4552
+ };
4553
+
4554
+ Object.defineProperty(exports, "useCurrentEditor", {
4555
+ enumerable: true,
4556
+ get: function () { return react.useCurrentEditor; }
4557
+ });
999
4558
  exports.Badge = Badge;
1000
4559
  exports.Button = Button;
1001
4560
  exports.ColorPicker = ColorPicker;
4561
+ exports.Highlight = Highlight;
4562
+ exports.HighlightButton = HighlightButton;
1002
4563
  exports.Input = Input;
4564
+ exports.PageBreak = PageBreak;
4565
+ exports.PageBreakButton = PageBreakButton;
1003
4566
  exports.RainCanvas = RainCanvas;
4567
+ exports.RichTextEditor = RichTextEditor;
4568
+ exports.SlidingCounter = SlidingCounter;
1004
4569
  exports.Timeline = Timeline;
1005
4570
  //# sourceMappingURL=index.cjs.map
1006
4571
  //# sourceMappingURL=index.cjs.map