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