@sethumadhavan004/ink-editor 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,2646 @@
1
+ // src/InkEditor.tsx
2
+ import { useEditor } from "@tiptap/react";
3
+ import StarterKit from "@tiptap/starter-kit";
4
+ import TextAlign from "@tiptap/extension-text-align";
5
+ import Underline2 from "@tiptap/extension-underline";
6
+ import { useEffect as useEffect4, useState as useState2 } from "react";
7
+
8
+ // node_modules/@tiptap/core/dist/index.js
9
+ import { Plugin, PluginKey, TextSelection, Selection, AllSelection, NodeSelection, EditorState } from "@tiptap/pm/state";
10
+ import { EditorView } from "@tiptap/pm/view";
11
+ import { keymap } from "@tiptap/pm/keymap";
12
+ import { Schema, DOMSerializer, Fragment, Node as Node$1, DOMParser, Slice } from "@tiptap/pm/model";
13
+ import { liftTarget, ReplaceStep, ReplaceAroundStep, joinPoint, Transform, canSplit, canJoin, findWrapping } from "@tiptap/pm/transform";
14
+ import { createParagraphNear as createParagraphNear$1, deleteSelection as deleteSelection$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";
15
+ import { liftListItem as liftListItem$1, sinkListItem as sinkListItem$1, wrapInList as wrapInList$1 } from "@tiptap/pm/schema-list";
16
+ function createChainableState(config) {
17
+ const { state, transaction } = config;
18
+ let { selection } = transaction;
19
+ let { doc } = transaction;
20
+ let { storedMarks } = transaction;
21
+ return {
22
+ ...state,
23
+ apply: state.apply.bind(state),
24
+ applyTransaction: state.applyTransaction.bind(state),
25
+ plugins: state.plugins,
26
+ schema: state.schema,
27
+ reconfigure: state.reconfigure.bind(state),
28
+ toJSON: state.toJSON.bind(state),
29
+ get storedMarks() {
30
+ return storedMarks;
31
+ },
32
+ get selection() {
33
+ return selection;
34
+ },
35
+ get doc() {
36
+ return doc;
37
+ },
38
+ get tr() {
39
+ selection = transaction.selection;
40
+ doc = transaction.doc;
41
+ storedMarks = transaction.storedMarks;
42
+ return transaction;
43
+ }
44
+ };
45
+ }
46
+ var CommandManager = class {
47
+ constructor(props) {
48
+ this.editor = props.editor;
49
+ this.rawCommands = this.editor.extensionManager.commands;
50
+ this.customState = props.state;
51
+ }
52
+ get hasCustomState() {
53
+ return !!this.customState;
54
+ }
55
+ get state() {
56
+ return this.customState || this.editor.state;
57
+ }
58
+ get commands() {
59
+ const { rawCommands, editor, state } = this;
60
+ const { view } = editor;
61
+ const { tr } = state;
62
+ const props = this.buildProps(tr);
63
+ return Object.fromEntries(Object.entries(rawCommands).map(([name, command2]) => {
64
+ const method = (...args) => {
65
+ const callback = command2(...args)(props);
66
+ if (!tr.getMeta("preventDispatch") && !this.hasCustomState) {
67
+ view.dispatch(tr);
68
+ }
69
+ return callback;
70
+ };
71
+ return [name, method];
72
+ }));
73
+ }
74
+ get chain() {
75
+ return () => this.createChain();
76
+ }
77
+ get can() {
78
+ return () => this.createCan();
79
+ }
80
+ createChain(startTr, shouldDispatch = true) {
81
+ const { rawCommands, editor, state } = this;
82
+ const { view } = editor;
83
+ const callbacks = [];
84
+ const hasStartTransaction = !!startTr;
85
+ const tr = startTr || state.tr;
86
+ const run = () => {
87
+ if (!hasStartTransaction && shouldDispatch && !tr.getMeta("preventDispatch") && !this.hasCustomState) {
88
+ view.dispatch(tr);
89
+ }
90
+ return callbacks.every((callback) => callback === true);
91
+ };
92
+ const chain = {
93
+ ...Object.fromEntries(Object.entries(rawCommands).map(([name, command2]) => {
94
+ const chainedCommand = (...args) => {
95
+ const props = this.buildProps(tr, shouldDispatch);
96
+ const callback = command2(...args)(props);
97
+ callbacks.push(callback);
98
+ return chain;
99
+ };
100
+ return [name, chainedCommand];
101
+ })),
102
+ run
103
+ };
104
+ return chain;
105
+ }
106
+ createCan(startTr) {
107
+ const { rawCommands, state } = this;
108
+ const dispatch = false;
109
+ const tr = startTr || state.tr;
110
+ const props = this.buildProps(tr, dispatch);
111
+ const formattedCommands = Object.fromEntries(Object.entries(rawCommands).map(([name, command2]) => {
112
+ return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })];
113
+ }));
114
+ return {
115
+ ...formattedCommands,
116
+ chain: () => this.createChain(tr, dispatch)
117
+ };
118
+ }
119
+ buildProps(tr, shouldDispatch = true) {
120
+ const { rawCommands, editor, state } = this;
121
+ const { view } = editor;
122
+ const props = {
123
+ tr,
124
+ editor,
125
+ view,
126
+ state: createChainableState({
127
+ state,
128
+ transaction: tr
129
+ }),
130
+ dispatch: shouldDispatch ? () => void 0 : void 0,
131
+ chain: () => this.createChain(tr, shouldDispatch),
132
+ can: () => this.createCan(tr),
133
+ get commands() {
134
+ return Object.fromEntries(Object.entries(rawCommands).map(([name, command2]) => {
135
+ return [name, (...args) => command2(...args)(props)];
136
+ }));
137
+ }
138
+ };
139
+ return props;
140
+ }
141
+ };
142
+ function getExtensionField(extension, field, context) {
143
+ if (extension.config[field] === void 0 && extension.parent) {
144
+ return getExtensionField(extension.parent, field, context);
145
+ }
146
+ if (typeof extension.config[field] === "function") {
147
+ const value = extension.config[field].bind({
148
+ ...context,
149
+ parent: extension.parent ? getExtensionField(extension.parent, field, context) : null
150
+ });
151
+ return value;
152
+ }
153
+ return extension.config[field];
154
+ }
155
+ function splitExtensions(extensions) {
156
+ const baseExtensions = extensions.filter((extension) => extension.type === "extension");
157
+ const nodeExtensions = extensions.filter((extension) => extension.type === "node");
158
+ const markExtensions = extensions.filter((extension) => extension.type === "mark");
159
+ return {
160
+ baseExtensions,
161
+ nodeExtensions,
162
+ markExtensions
163
+ };
164
+ }
165
+ function getNodeType(nameOrType, schema) {
166
+ if (typeof nameOrType === "string") {
167
+ if (!schema.nodes[nameOrType]) {
168
+ throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`);
169
+ }
170
+ return schema.nodes[nameOrType];
171
+ }
172
+ return nameOrType;
173
+ }
174
+ function isFunction(value) {
175
+ return typeof value === "function";
176
+ }
177
+ function callOrReturn(value, context = void 0, ...props) {
178
+ if (isFunction(value)) {
179
+ if (context) {
180
+ return value.bind(context)(...props);
181
+ }
182
+ return value(...props);
183
+ }
184
+ return value;
185
+ }
186
+ function isRegExp(value) {
187
+ return Object.prototype.toString.call(value) === "[object RegExp]";
188
+ }
189
+ function getType(value) {
190
+ return Object.prototype.toString.call(value).slice(8, -1);
191
+ }
192
+ function isPlainObject(value) {
193
+ if (getType(value) !== "Object") {
194
+ return false;
195
+ }
196
+ return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype;
197
+ }
198
+ function mergeDeep(target, source) {
199
+ const output = { ...target };
200
+ if (isPlainObject(target) && isPlainObject(source)) {
201
+ Object.keys(source).forEach((key) => {
202
+ if (isPlainObject(source[key]) && isPlainObject(target[key])) {
203
+ output[key] = mergeDeep(target[key], source[key]);
204
+ } else {
205
+ output[key] = source[key];
206
+ }
207
+ });
208
+ }
209
+ return output;
210
+ }
211
+ var Extension = class _Extension {
212
+ constructor(config = {}) {
213
+ this.type = "extension";
214
+ this.name = "extension";
215
+ this.parent = null;
216
+ this.child = null;
217
+ this.config = {
218
+ name: this.name,
219
+ defaultOptions: {}
220
+ };
221
+ this.config = {
222
+ ...this.config,
223
+ ...config
224
+ };
225
+ this.name = this.config.name;
226
+ if (config.defaultOptions && Object.keys(config.defaultOptions).length > 0) {
227
+ console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`);
228
+ }
229
+ this.options = this.config.defaultOptions;
230
+ if (this.config.addOptions) {
231
+ this.options = callOrReturn(getExtensionField(this, "addOptions", {
232
+ name: this.name
233
+ }));
234
+ }
235
+ this.storage = callOrReturn(getExtensionField(this, "addStorage", {
236
+ name: this.name,
237
+ options: this.options
238
+ })) || {};
239
+ }
240
+ static create(config = {}) {
241
+ return new _Extension(config);
242
+ }
243
+ configure(options = {}) {
244
+ const extension = this.extend({
245
+ ...this.config,
246
+ addOptions: () => {
247
+ return mergeDeep(this.options, options);
248
+ }
249
+ });
250
+ extension.name = this.name;
251
+ extension.parent = this.parent;
252
+ return extension;
253
+ }
254
+ extend(extendedConfig = {}) {
255
+ const extension = new _Extension({ ...this.config, ...extendedConfig });
256
+ extension.parent = this;
257
+ this.child = extension;
258
+ extension.name = extendedConfig.name ? extendedConfig.name : extension.parent.name;
259
+ if (extendedConfig.defaultOptions && Object.keys(extendedConfig.defaultOptions).length > 0) {
260
+ console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${extension.name}".`);
261
+ }
262
+ extension.options = callOrReturn(getExtensionField(extension, "addOptions", {
263
+ name: extension.name
264
+ }));
265
+ extension.storage = callOrReturn(getExtensionField(extension, "addStorage", {
266
+ name: extension.name,
267
+ options: extension.options
268
+ }));
269
+ return extension;
270
+ }
271
+ };
272
+ function getTextBetween(startNode, range, options) {
273
+ const { from, to } = range;
274
+ const { blockSeparator = "\n\n", textSerializers = {} } = options || {};
275
+ let text = "";
276
+ startNode.nodesBetween(from, to, (node, pos, parent, index) => {
277
+ var _a;
278
+ if (node.isBlock && pos > from) {
279
+ text += blockSeparator;
280
+ }
281
+ const textSerializer = textSerializers === null || textSerializers === void 0 ? void 0 : textSerializers[node.type.name];
282
+ if (textSerializer) {
283
+ if (parent) {
284
+ text += textSerializer({
285
+ node,
286
+ pos,
287
+ parent,
288
+ index,
289
+ range
290
+ });
291
+ }
292
+ return false;
293
+ }
294
+ if (node.isText) {
295
+ text += (_a = node === null || node === void 0 ? void 0 : node.text) === null || _a === void 0 ? void 0 : _a.slice(Math.max(from, pos) - pos, to - pos);
296
+ }
297
+ });
298
+ return text;
299
+ }
300
+ function getTextSerializersFromSchema(schema) {
301
+ return Object.fromEntries(Object.entries(schema.nodes).filter(([, node]) => node.spec.toText).map(([name, node]) => [name, node.spec.toText]));
302
+ }
303
+ var ClipboardTextSerializer = Extension.create({
304
+ name: "clipboardTextSerializer",
305
+ addOptions() {
306
+ return {
307
+ blockSeparator: void 0
308
+ };
309
+ },
310
+ addProseMirrorPlugins() {
311
+ return [
312
+ new Plugin({
313
+ key: new PluginKey("clipboardTextSerializer"),
314
+ props: {
315
+ clipboardTextSerializer: () => {
316
+ const { editor } = this;
317
+ const { state, schema } = editor;
318
+ const { doc, selection } = state;
319
+ const { ranges } = selection;
320
+ const from = Math.min(...ranges.map((range2) => range2.$from.pos));
321
+ const to = Math.max(...ranges.map((range2) => range2.$to.pos));
322
+ const textSerializers = getTextSerializersFromSchema(schema);
323
+ const range = { from, to };
324
+ return getTextBetween(doc, range, {
325
+ ...this.options.blockSeparator !== void 0 ? { blockSeparator: this.options.blockSeparator } : {},
326
+ textSerializers
327
+ });
328
+ }
329
+ }
330
+ })
331
+ ];
332
+ }
333
+ });
334
+ var blur = () => ({ editor, view }) => {
335
+ requestAnimationFrame(() => {
336
+ var _a;
337
+ if (!editor.isDestroyed) {
338
+ view.dom.blur();
339
+ (_a = window === null || window === void 0 ? void 0 : window.getSelection()) === null || _a === void 0 ? void 0 : _a.removeAllRanges();
340
+ }
341
+ });
342
+ return true;
343
+ };
344
+ var clearContent = (emitUpdate = false) => ({ commands: commands2 }) => {
345
+ return commands2.setContent("", emitUpdate);
346
+ };
347
+ var clearNodes = () => ({ state, tr, dispatch }) => {
348
+ const { selection } = tr;
349
+ const { ranges } = selection;
350
+ if (!dispatch) {
351
+ return true;
352
+ }
353
+ ranges.forEach(({ $from, $to }) => {
354
+ state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
355
+ if (node.type.isText) {
356
+ return;
357
+ }
358
+ const { doc, mapping } = tr;
359
+ const $mappedFrom = doc.resolve(mapping.map(pos));
360
+ const $mappedTo = doc.resolve(mapping.map(pos + node.nodeSize));
361
+ const nodeRange = $mappedFrom.blockRange($mappedTo);
362
+ if (!nodeRange) {
363
+ return;
364
+ }
365
+ const targetLiftDepth = liftTarget(nodeRange);
366
+ if (node.type.isTextblock) {
367
+ const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index());
368
+ tr.setNodeMarkup(nodeRange.start, defaultType);
369
+ }
370
+ if (targetLiftDepth || targetLiftDepth === 0) {
371
+ tr.lift(nodeRange, targetLiftDepth);
372
+ }
373
+ });
374
+ });
375
+ return true;
376
+ };
377
+ var command = (fn) => (props) => {
378
+ return fn(props);
379
+ };
380
+ var createParagraphNear = () => ({ state, dispatch }) => {
381
+ return createParagraphNear$1(state, dispatch);
382
+ };
383
+ var cut = (originRange, targetPos) => ({ editor, tr }) => {
384
+ const { state } = editor;
385
+ const contentSlice = state.doc.slice(originRange.from, originRange.to);
386
+ tr.deleteRange(originRange.from, originRange.to);
387
+ const newPos = tr.mapping.map(targetPos);
388
+ tr.insert(newPos, contentSlice.content);
389
+ tr.setSelection(new TextSelection(tr.doc.resolve(Math.max(newPos - 1, 0))));
390
+ return true;
391
+ };
392
+ var deleteCurrentNode = () => ({ tr, dispatch }) => {
393
+ const { selection } = tr;
394
+ const currentNode = selection.$anchor.node();
395
+ if (currentNode.content.size > 0) {
396
+ return false;
397
+ }
398
+ const $pos = tr.selection.$anchor;
399
+ for (let depth = $pos.depth; depth > 0; depth -= 1) {
400
+ const node = $pos.node(depth);
401
+ if (node.type === currentNode.type) {
402
+ if (dispatch) {
403
+ const from = $pos.before(depth);
404
+ const to = $pos.after(depth);
405
+ tr.delete(from, to).scrollIntoView();
406
+ }
407
+ return true;
408
+ }
409
+ }
410
+ return false;
411
+ };
412
+ var deleteNode = (typeOrName) => ({ tr, state, dispatch }) => {
413
+ const type = getNodeType(typeOrName, state.schema);
414
+ const $pos = tr.selection.$anchor;
415
+ for (let depth = $pos.depth; depth > 0; depth -= 1) {
416
+ const node = $pos.node(depth);
417
+ if (node.type === type) {
418
+ if (dispatch) {
419
+ const from = $pos.before(depth);
420
+ const to = $pos.after(depth);
421
+ tr.delete(from, to).scrollIntoView();
422
+ }
423
+ return true;
424
+ }
425
+ }
426
+ return false;
427
+ };
428
+ var deleteRange = (range) => ({ tr, dispatch }) => {
429
+ const { from, to } = range;
430
+ if (dispatch) {
431
+ tr.delete(from, to);
432
+ }
433
+ return true;
434
+ };
435
+ var deleteSelection = () => ({ state, dispatch }) => {
436
+ return deleteSelection$1(state, dispatch);
437
+ };
438
+ var enter = () => ({ commands: commands2 }) => {
439
+ return commands2.keyboardShortcut("Enter");
440
+ };
441
+ var exitCode = () => ({ state, dispatch }) => {
442
+ return exitCode$1(state, dispatch);
443
+ };
444
+ function objectIncludes(object1, object2, options = { strict: true }) {
445
+ const keys = Object.keys(object2);
446
+ if (!keys.length) {
447
+ return true;
448
+ }
449
+ return keys.every((key) => {
450
+ if (options.strict) {
451
+ return object2[key] === object1[key];
452
+ }
453
+ if (isRegExp(object2[key])) {
454
+ return object2[key].test(object1[key]);
455
+ }
456
+ return object2[key] === object1[key];
457
+ });
458
+ }
459
+ function findMarkInSet(marks, type, attributes = {}) {
460
+ return marks.find((item) => {
461
+ return item.type === type && objectIncludes(
462
+ // Only check equality for the attributes that are provided
463
+ Object.fromEntries(Object.keys(attributes).map((k) => [k, item.attrs[k]])),
464
+ attributes
465
+ );
466
+ });
467
+ }
468
+ function isMarkInSet(marks, type, attributes = {}) {
469
+ return !!findMarkInSet(marks, type, attributes);
470
+ }
471
+ function getMarkRange($pos, type, attributes) {
472
+ var _a;
473
+ if (!$pos || !type) {
474
+ return;
475
+ }
476
+ let start = $pos.parent.childAfter($pos.parentOffset);
477
+ if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) {
478
+ start = $pos.parent.childBefore($pos.parentOffset);
479
+ }
480
+ if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) {
481
+ return;
482
+ }
483
+ attributes = attributes || ((_a = start.node.marks[0]) === null || _a === void 0 ? void 0 : _a.attrs);
484
+ const mark = findMarkInSet([...start.node.marks], type, attributes);
485
+ if (!mark) {
486
+ return;
487
+ }
488
+ let startIndex = start.index;
489
+ let startPos = $pos.start() + start.offset;
490
+ let endIndex = startIndex + 1;
491
+ let endPos = startPos + start.node.nodeSize;
492
+ while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) {
493
+ startIndex -= 1;
494
+ startPos -= $pos.parent.child(startIndex).nodeSize;
495
+ }
496
+ while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) {
497
+ endPos += $pos.parent.child(endIndex).nodeSize;
498
+ endIndex += 1;
499
+ }
500
+ return {
501
+ from: startPos,
502
+ to: endPos
503
+ };
504
+ }
505
+ function getMarkType(nameOrType, schema) {
506
+ if (typeof nameOrType === "string") {
507
+ if (!schema.marks[nameOrType]) {
508
+ throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`);
509
+ }
510
+ return schema.marks[nameOrType];
511
+ }
512
+ return nameOrType;
513
+ }
514
+ var extendMarkRange = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
515
+ const type = getMarkType(typeOrName, state.schema);
516
+ const { doc, selection } = tr;
517
+ const { $from, from, to } = selection;
518
+ if (dispatch) {
519
+ const range = getMarkRange($from, type, attributes);
520
+ if (range && range.from <= from && range.to >= to) {
521
+ const newSelection = TextSelection.create(doc, range.from, range.to);
522
+ tr.setSelection(newSelection);
523
+ }
524
+ }
525
+ return true;
526
+ };
527
+ var first = (commands2) => (props) => {
528
+ const items = typeof commands2 === "function" ? commands2(props) : commands2;
529
+ for (let i = 0; i < items.length; i += 1) {
530
+ if (items[i](props)) {
531
+ return true;
532
+ }
533
+ }
534
+ return false;
535
+ };
536
+ function isTextSelection(value) {
537
+ return value instanceof TextSelection;
538
+ }
539
+ function minMax(value = 0, min = 0, max = 0) {
540
+ return Math.min(Math.max(value, min), max);
541
+ }
542
+ function resolveFocusPosition(doc, position = null) {
543
+ if (!position) {
544
+ return null;
545
+ }
546
+ const selectionAtStart = Selection.atStart(doc);
547
+ const selectionAtEnd = Selection.atEnd(doc);
548
+ if (position === "start" || position === true) {
549
+ return selectionAtStart;
550
+ }
551
+ if (position === "end") {
552
+ return selectionAtEnd;
553
+ }
554
+ const minPos = selectionAtStart.from;
555
+ const maxPos = selectionAtEnd.to;
556
+ if (position === "all") {
557
+ return TextSelection.create(doc, minMax(0, minPos, maxPos), minMax(doc.content.size, minPos, maxPos));
558
+ }
559
+ return TextSelection.create(doc, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos));
560
+ }
561
+ function isAndroid() {
562
+ return navigator.platform === "Android" || /android/i.test(navigator.userAgent);
563
+ }
564
+ function isiOS() {
565
+ return [
566
+ "iPad Simulator",
567
+ "iPhone Simulator",
568
+ "iPod Simulator",
569
+ "iPad",
570
+ "iPhone",
571
+ "iPod"
572
+ ].includes(navigator.platform) || navigator.userAgent.includes("Mac") && "ontouchend" in document;
573
+ }
574
+ function isSafari() {
575
+ return typeof navigator !== "undefined" ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false;
576
+ }
577
+ var focus = (position = null, options = {}) => ({ editor, view, tr, dispatch }) => {
578
+ options = {
579
+ scrollIntoView: true,
580
+ ...options
581
+ };
582
+ const delayedFocus = () => {
583
+ if (isiOS() || isAndroid()) {
584
+ view.dom.focus();
585
+ }
586
+ requestAnimationFrame(() => {
587
+ if (!editor.isDestroyed) {
588
+ view.focus();
589
+ if (isSafari() && !isiOS() && !isAndroid()) {
590
+ view.dom.focus({ preventScroll: true });
591
+ }
592
+ }
593
+ });
594
+ };
595
+ if (view.hasFocus() && position === null || position === false) {
596
+ return true;
597
+ }
598
+ if (dispatch && position === null && !isTextSelection(editor.state.selection)) {
599
+ delayedFocus();
600
+ return true;
601
+ }
602
+ const selection = resolveFocusPosition(tr.doc, position) || editor.state.selection;
603
+ const isSameSelection = editor.state.selection.eq(selection);
604
+ if (dispatch) {
605
+ if (!isSameSelection) {
606
+ tr.setSelection(selection);
607
+ }
608
+ if (isSameSelection && tr.storedMarks) {
609
+ tr.setStoredMarks(tr.storedMarks);
610
+ }
611
+ delayedFocus();
612
+ }
613
+ return true;
614
+ };
615
+ var forEach = (items, fn) => (props) => {
616
+ return items.every((item, index) => fn(item, { ...props, index }));
617
+ };
618
+ var insertContent = (value, options) => ({ tr, commands: commands2 }) => {
619
+ return commands2.insertContentAt({ from: tr.selection.from, to: tr.selection.to }, value, options);
620
+ };
621
+ var removeWhitespaces = (node) => {
622
+ const children = node.childNodes;
623
+ for (let i = children.length - 1; i >= 0; i -= 1) {
624
+ const child = children[i];
625
+ if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) {
626
+ node.removeChild(child);
627
+ } else if (child.nodeType === 1) {
628
+ removeWhitespaces(child);
629
+ }
630
+ }
631
+ return node;
632
+ };
633
+ function elementFromString(value) {
634
+ const wrappedValue = `<body>${value}</body>`;
635
+ const html = new window.DOMParser().parseFromString(wrappedValue, "text/html").body;
636
+ return removeWhitespaces(html);
637
+ }
638
+ function createNodeFromContent(content, schema, options) {
639
+ if (content instanceof Node$1 || content instanceof Fragment) {
640
+ return content;
641
+ }
642
+ options = {
643
+ slice: true,
644
+ parseOptions: {},
645
+ ...options
646
+ };
647
+ const isJSONContent = typeof content === "object" && content !== null;
648
+ const isTextContent = typeof content === "string";
649
+ if (isJSONContent) {
650
+ try {
651
+ const isArrayContent = Array.isArray(content) && content.length > 0;
652
+ if (isArrayContent) {
653
+ return Fragment.fromArray(content.map((item) => schema.nodeFromJSON(item)));
654
+ }
655
+ const node = schema.nodeFromJSON(content);
656
+ if (options.errorOnInvalidContent) {
657
+ node.check();
658
+ }
659
+ return node;
660
+ } catch (error) {
661
+ if (options.errorOnInvalidContent) {
662
+ throw new Error("[tiptap error]: Invalid JSON content", { cause: error });
663
+ }
664
+ console.warn("[tiptap warn]: Invalid content.", "Passed value:", content, "Error:", error);
665
+ return createNodeFromContent("", schema, options);
666
+ }
667
+ }
668
+ if (isTextContent) {
669
+ if (options.errorOnInvalidContent) {
670
+ let hasInvalidContent = false;
671
+ let invalidContent = "";
672
+ const contentCheckSchema = new Schema({
673
+ topNode: schema.spec.topNode,
674
+ marks: schema.spec.marks,
675
+ // Prosemirror's schemas are executed such that: the last to execute, matches last
676
+ // 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
677
+ nodes: schema.spec.nodes.append({
678
+ __tiptap__private__unknown__catch__all__node: {
679
+ content: "inline*",
680
+ group: "block",
681
+ parseDOM: [
682
+ {
683
+ tag: "*",
684
+ getAttrs: (e) => {
685
+ hasInvalidContent = true;
686
+ invalidContent = typeof e === "string" ? e : e.outerHTML;
687
+ return null;
688
+ }
689
+ }
690
+ ]
691
+ }
692
+ })
693
+ });
694
+ if (options.slice) {
695
+ DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions);
696
+ } else {
697
+ DOMParser.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions);
698
+ }
699
+ if (options.errorOnInvalidContent && hasInvalidContent) {
700
+ throw new Error("[tiptap error]: Invalid HTML content", { cause: new Error(`Invalid element found: ${invalidContent}`) });
701
+ }
702
+ }
703
+ const parser = DOMParser.fromSchema(schema);
704
+ if (options.slice) {
705
+ return parser.parseSlice(elementFromString(content), options.parseOptions).content;
706
+ }
707
+ return parser.parse(elementFromString(content), options.parseOptions);
708
+ }
709
+ return createNodeFromContent("", schema, options);
710
+ }
711
+ function selectionToInsertionEnd(tr, startLen, bias) {
712
+ const last = tr.steps.length - 1;
713
+ if (last < startLen) {
714
+ return;
715
+ }
716
+ const step = tr.steps[last];
717
+ if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {
718
+ return;
719
+ }
720
+ const map = tr.mapping.maps[last];
721
+ let end = 0;
722
+ map.forEach((_from, _to, _newFrom, newTo) => {
723
+ if (end === 0) {
724
+ end = newTo;
725
+ }
726
+ });
727
+ tr.setSelection(Selection.near(tr.doc.resolve(end), bias));
728
+ }
729
+ var isFragment = (nodeOrFragment) => {
730
+ return !("type" in nodeOrFragment);
731
+ };
732
+ var insertContentAt = (position, value, options) => ({ tr, dispatch, editor }) => {
733
+ var _a;
734
+ if (dispatch) {
735
+ options = {
736
+ parseOptions: editor.options.parseOptions,
737
+ updateSelection: true,
738
+ applyInputRules: false,
739
+ applyPasteRules: false,
740
+ ...options
741
+ };
742
+ let content;
743
+ const emitContentError = (error) => {
744
+ editor.emit("contentError", {
745
+ editor,
746
+ error,
747
+ disableCollaboration: () => {
748
+ if (editor.storage.collaboration) {
749
+ editor.storage.collaboration.isDisabled = true;
750
+ }
751
+ }
752
+ });
753
+ };
754
+ const parseOptions = {
755
+ preserveWhitespace: "full",
756
+ ...options.parseOptions
757
+ };
758
+ if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) {
759
+ try {
760
+ createNodeFromContent(value, editor.schema, {
761
+ parseOptions,
762
+ errorOnInvalidContent: true
763
+ });
764
+ } catch (e) {
765
+ emitContentError(e);
766
+ }
767
+ }
768
+ try {
769
+ content = createNodeFromContent(value, editor.schema, {
770
+ parseOptions,
771
+ errorOnInvalidContent: (_a = options.errorOnInvalidContent) !== null && _a !== void 0 ? _a : editor.options.enableContentCheck
772
+ });
773
+ } catch (e) {
774
+ emitContentError(e);
775
+ return false;
776
+ }
777
+ let { from, to } = typeof position === "number" ? { from: position, to: position } : { from: position.from, to: position.to };
778
+ let isOnlyTextContent = true;
779
+ let isOnlyBlockContent = true;
780
+ const nodes = isFragment(content) ? content : [content];
781
+ nodes.forEach((node) => {
782
+ node.check();
783
+ isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false;
784
+ isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false;
785
+ });
786
+ if (from === to && isOnlyBlockContent) {
787
+ const { parent } = tr.doc.resolve(from);
788
+ const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount;
789
+ if (isEmptyTextBlock) {
790
+ from -= 1;
791
+ to += 1;
792
+ }
793
+ }
794
+ let newContent;
795
+ if (isOnlyTextContent) {
796
+ if (Array.isArray(value)) {
797
+ newContent = value.map((v) => v.text || "").join("");
798
+ } else if (value instanceof Fragment) {
799
+ let text = "";
800
+ value.forEach((node) => {
801
+ if (node.text) {
802
+ text += node.text;
803
+ }
804
+ });
805
+ newContent = text;
806
+ } else if (typeof value === "object" && !!value && !!value.text) {
807
+ newContent = value.text;
808
+ } else {
809
+ newContent = value;
810
+ }
811
+ tr.insertText(newContent, from, to);
812
+ } else {
813
+ newContent = content;
814
+ tr.replaceWith(from, to, newContent);
815
+ }
816
+ if (options.updateSelection) {
817
+ selectionToInsertionEnd(tr, tr.steps.length - 1, -1);
818
+ }
819
+ if (options.applyInputRules) {
820
+ tr.setMeta("applyInputRules", { from, text: newContent });
821
+ }
822
+ if (options.applyPasteRules) {
823
+ tr.setMeta("applyPasteRules", { from, text: newContent });
824
+ }
825
+ }
826
+ return true;
827
+ };
828
+ var joinUp = () => ({ state, dispatch }) => {
829
+ return joinUp$1(state, dispatch);
830
+ };
831
+ var joinDown = () => ({ state, dispatch }) => {
832
+ return joinDown$1(state, dispatch);
833
+ };
834
+ var joinBackward = () => ({ state, dispatch }) => {
835
+ return joinBackward$1(state, dispatch);
836
+ };
837
+ var joinForward = () => ({ state, dispatch }) => {
838
+ return joinForward$1(state, dispatch);
839
+ };
840
+ var joinItemBackward = () => ({ state, dispatch, tr }) => {
841
+ try {
842
+ const point = joinPoint(state.doc, state.selection.$from.pos, -1);
843
+ if (point === null || point === void 0) {
844
+ return false;
845
+ }
846
+ tr.join(point, 2);
847
+ if (dispatch) {
848
+ dispatch(tr);
849
+ }
850
+ return true;
851
+ } catch {
852
+ return false;
853
+ }
854
+ };
855
+ var joinItemForward = () => ({ state, dispatch, tr }) => {
856
+ try {
857
+ const point = joinPoint(state.doc, state.selection.$from.pos, 1);
858
+ if (point === null || point === void 0) {
859
+ return false;
860
+ }
861
+ tr.join(point, 2);
862
+ if (dispatch) {
863
+ dispatch(tr);
864
+ }
865
+ return true;
866
+ } catch {
867
+ return false;
868
+ }
869
+ };
870
+ var joinTextblockBackward = () => ({ state, dispatch }) => {
871
+ return joinTextblockBackward$1(state, dispatch);
872
+ };
873
+ var joinTextblockForward = () => ({ state, dispatch }) => {
874
+ return joinTextblockForward$1(state, dispatch);
875
+ };
876
+ function isMacOS() {
877
+ return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
878
+ }
879
+ function normalizeKeyName(name) {
880
+ const parts = name.split(/-(?!$)/);
881
+ let result = parts[parts.length - 1];
882
+ if (result === "Space") {
883
+ result = " ";
884
+ }
885
+ let alt;
886
+ let ctrl;
887
+ let shift;
888
+ let meta;
889
+ for (let i = 0; i < parts.length - 1; i += 1) {
890
+ const mod = parts[i];
891
+ if (/^(cmd|meta|m)$/i.test(mod)) {
892
+ meta = true;
893
+ } else if (/^a(lt)?$/i.test(mod)) {
894
+ alt = true;
895
+ } else if (/^(c|ctrl|control)$/i.test(mod)) {
896
+ ctrl = true;
897
+ } else if (/^s(hift)?$/i.test(mod)) {
898
+ shift = true;
899
+ } else if (/^mod$/i.test(mod)) {
900
+ if (isiOS() || isMacOS()) {
901
+ meta = true;
902
+ } else {
903
+ ctrl = true;
904
+ }
905
+ } else {
906
+ throw new Error(`Unrecognized modifier name: ${mod}`);
907
+ }
908
+ }
909
+ if (alt) {
910
+ result = `Alt-${result}`;
911
+ }
912
+ if (ctrl) {
913
+ result = `Ctrl-${result}`;
914
+ }
915
+ if (meta) {
916
+ result = `Meta-${result}`;
917
+ }
918
+ if (shift) {
919
+ result = `Shift-${result}`;
920
+ }
921
+ return result;
922
+ }
923
+ var keyboardShortcut = (name) => ({ editor, view, tr, dispatch }) => {
924
+ const keys = normalizeKeyName(name).split(/-(?!$)/);
925
+ const key = keys.find((item) => !["Alt", "Ctrl", "Meta", "Shift"].includes(item));
926
+ const event = new KeyboardEvent("keydown", {
927
+ key: key === "Space" ? " " : key,
928
+ altKey: keys.includes("Alt"),
929
+ ctrlKey: keys.includes("Ctrl"),
930
+ metaKey: keys.includes("Meta"),
931
+ shiftKey: keys.includes("Shift"),
932
+ bubbles: true,
933
+ cancelable: true
934
+ });
935
+ const capturedTransaction = editor.captureTransaction(() => {
936
+ view.someProp("handleKeyDown", (f) => f(view, event));
937
+ });
938
+ capturedTransaction === null || capturedTransaction === void 0 ? void 0 : capturedTransaction.steps.forEach((step) => {
939
+ const newStep = step.map(tr.mapping);
940
+ if (newStep && dispatch) {
941
+ tr.maybeStep(newStep);
942
+ }
943
+ });
944
+ return true;
945
+ };
946
+ function isNodeActive(state, typeOrName, attributes = {}) {
947
+ const { from, to, empty } = state.selection;
948
+ const type = typeOrName ? getNodeType(typeOrName, state.schema) : null;
949
+ const nodeRanges = [];
950
+ state.doc.nodesBetween(from, to, (node, pos) => {
951
+ if (node.isText) {
952
+ return;
953
+ }
954
+ const relativeFrom = Math.max(from, pos);
955
+ const relativeTo = Math.min(to, pos + node.nodeSize);
956
+ nodeRanges.push({
957
+ node,
958
+ from: relativeFrom,
959
+ to: relativeTo
960
+ });
961
+ });
962
+ const selectionRange = to - from;
963
+ const matchedNodeRanges = nodeRanges.filter((nodeRange) => {
964
+ if (!type) {
965
+ return true;
966
+ }
967
+ return type.name === nodeRange.node.type.name;
968
+ }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }));
969
+ if (empty) {
970
+ return !!matchedNodeRanges.length;
971
+ }
972
+ const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0);
973
+ return range >= selectionRange;
974
+ }
975
+ var lift = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
976
+ const type = getNodeType(typeOrName, state.schema);
977
+ const isActive = isNodeActive(state, type, attributes);
978
+ if (!isActive) {
979
+ return false;
980
+ }
981
+ return lift$1(state, dispatch);
982
+ };
983
+ var liftEmptyBlock = () => ({ state, dispatch }) => {
984
+ return liftEmptyBlock$1(state, dispatch);
985
+ };
986
+ var liftListItem = (typeOrName) => ({ state, dispatch }) => {
987
+ const type = getNodeType(typeOrName, state.schema);
988
+ return liftListItem$1(type)(state, dispatch);
989
+ };
990
+ var newlineInCode = () => ({ state, dispatch }) => {
991
+ return newlineInCode$1(state, dispatch);
992
+ };
993
+ function getSchemaTypeNameByName(name, schema) {
994
+ if (schema.nodes[name]) {
995
+ return "node";
996
+ }
997
+ if (schema.marks[name]) {
998
+ return "mark";
999
+ }
1000
+ return null;
1001
+ }
1002
+ function deleteProps(obj, propOrProps) {
1003
+ const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps;
1004
+ return Object.keys(obj).reduce((newObj, prop) => {
1005
+ if (!props.includes(prop)) {
1006
+ newObj[prop] = obj[prop];
1007
+ }
1008
+ return newObj;
1009
+ }, {});
1010
+ }
1011
+ var resetAttributes = (typeOrName, attributes) => ({ tr, state, dispatch }) => {
1012
+ let nodeType = null;
1013
+ let markType = null;
1014
+ const schemaType = getSchemaTypeNameByName(typeof typeOrName === "string" ? typeOrName : typeOrName.name, state.schema);
1015
+ if (!schemaType) {
1016
+ return false;
1017
+ }
1018
+ if (schemaType === "node") {
1019
+ nodeType = getNodeType(typeOrName, state.schema);
1020
+ }
1021
+ if (schemaType === "mark") {
1022
+ markType = getMarkType(typeOrName, state.schema);
1023
+ }
1024
+ if (dispatch) {
1025
+ tr.selection.ranges.forEach((range) => {
1026
+ state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {
1027
+ if (nodeType && nodeType === node.type) {
1028
+ tr.setNodeMarkup(pos, void 0, deleteProps(node.attrs, attributes));
1029
+ }
1030
+ if (markType && node.marks.length) {
1031
+ node.marks.forEach((mark) => {
1032
+ if (markType === mark.type) {
1033
+ tr.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes)));
1034
+ }
1035
+ });
1036
+ }
1037
+ });
1038
+ });
1039
+ }
1040
+ return true;
1041
+ };
1042
+ var scrollIntoView = () => ({ tr, dispatch }) => {
1043
+ if (dispatch) {
1044
+ tr.scrollIntoView();
1045
+ }
1046
+ return true;
1047
+ };
1048
+ var selectAll = () => ({ tr, dispatch }) => {
1049
+ if (dispatch) {
1050
+ const selection = new AllSelection(tr.doc);
1051
+ tr.setSelection(selection);
1052
+ }
1053
+ return true;
1054
+ };
1055
+ var selectNodeBackward = () => ({ state, dispatch }) => {
1056
+ return selectNodeBackward$1(state, dispatch);
1057
+ };
1058
+ var selectNodeForward = () => ({ state, dispatch }) => {
1059
+ return selectNodeForward$1(state, dispatch);
1060
+ };
1061
+ var selectParentNode = () => ({ state, dispatch }) => {
1062
+ return selectParentNode$1(state, dispatch);
1063
+ };
1064
+ var selectTextblockEnd = () => ({ state, dispatch }) => {
1065
+ return selectTextblockEnd$1(state, dispatch);
1066
+ };
1067
+ var selectTextblockStart = () => ({ state, dispatch }) => {
1068
+ return selectTextblockStart$1(state, dispatch);
1069
+ };
1070
+ function createDocument(content, schema, parseOptions = {}, options = {}) {
1071
+ return createNodeFromContent(content, schema, {
1072
+ slice: false,
1073
+ parseOptions,
1074
+ errorOnInvalidContent: options.errorOnInvalidContent
1075
+ });
1076
+ }
1077
+ var setContent = (content, emitUpdate = false, parseOptions = {}, options = {}) => ({ editor, tr, dispatch, commands: commands2 }) => {
1078
+ var _a, _b;
1079
+ const { doc } = tr;
1080
+ if (parseOptions.preserveWhitespace !== "full") {
1081
+ const document2 = createDocument(content, editor.schema, parseOptions, {
1082
+ errorOnInvalidContent: (_a = options.errorOnInvalidContent) !== null && _a !== void 0 ? _a : editor.options.enableContentCheck
1083
+ });
1084
+ if (dispatch) {
1085
+ tr.replaceWith(0, doc.content.size, document2).setMeta("preventUpdate", !emitUpdate);
1086
+ }
1087
+ return true;
1088
+ }
1089
+ if (dispatch) {
1090
+ tr.setMeta("preventUpdate", !emitUpdate);
1091
+ }
1092
+ return commands2.insertContentAt({ from: 0, to: doc.content.size }, content, {
1093
+ parseOptions,
1094
+ errorOnInvalidContent: (_b = options.errorOnInvalidContent) !== null && _b !== void 0 ? _b : editor.options.enableContentCheck
1095
+ });
1096
+ };
1097
+ function getMarkAttributes(state, typeOrName) {
1098
+ const type = getMarkType(typeOrName, state.schema);
1099
+ const { from, to, empty } = state.selection;
1100
+ const marks = [];
1101
+ if (empty) {
1102
+ if (state.storedMarks) {
1103
+ marks.push(...state.storedMarks);
1104
+ }
1105
+ marks.push(...state.selection.$head.marks());
1106
+ } else {
1107
+ state.doc.nodesBetween(from, to, (node) => {
1108
+ marks.push(...node.marks);
1109
+ });
1110
+ }
1111
+ const mark = marks.find((markItem) => markItem.type.name === type.name);
1112
+ if (!mark) {
1113
+ return {};
1114
+ }
1115
+ return { ...mark.attrs };
1116
+ }
1117
+ function defaultBlockAt(match) {
1118
+ for (let i = 0; i < match.edgeCount; i += 1) {
1119
+ const { type } = match.edge(i);
1120
+ if (type.isTextblock && !type.hasRequiredAttrs()) {
1121
+ return type;
1122
+ }
1123
+ }
1124
+ return null;
1125
+ }
1126
+ function findParentNodeClosestToPos($pos, predicate) {
1127
+ for (let i = $pos.depth; i > 0; i -= 1) {
1128
+ const node = $pos.node(i);
1129
+ if (predicate(node)) {
1130
+ return {
1131
+ pos: i > 0 ? $pos.before(i) : 0,
1132
+ start: $pos.start(i),
1133
+ depth: i,
1134
+ node
1135
+ };
1136
+ }
1137
+ }
1138
+ }
1139
+ function findParentNode(predicate) {
1140
+ return (selection) => findParentNodeClosestToPos(selection.$from, predicate);
1141
+ }
1142
+ function getSplittedAttributes(extensionAttributes, typeName, attributes) {
1143
+ return Object.fromEntries(Object.entries(attributes).filter(([name]) => {
1144
+ const extensionAttribute = extensionAttributes.find((item) => {
1145
+ return item.type === typeName && item.name === name;
1146
+ });
1147
+ if (!extensionAttribute) {
1148
+ return false;
1149
+ }
1150
+ return extensionAttribute.attribute.keepOnSplit;
1151
+ }));
1152
+ }
1153
+ function isMarkActive(state, typeOrName, attributes = {}) {
1154
+ const { empty, ranges } = state.selection;
1155
+ const type = typeOrName ? getMarkType(typeOrName, state.schema) : null;
1156
+ if (empty) {
1157
+ return !!(state.storedMarks || state.selection.$from.marks()).filter((mark) => {
1158
+ if (!type) {
1159
+ return true;
1160
+ }
1161
+ return type.name === mark.type.name;
1162
+ }).find((mark) => objectIncludes(mark.attrs, attributes, { strict: false }));
1163
+ }
1164
+ let selectionRange = 0;
1165
+ const markRanges = [];
1166
+ ranges.forEach(({ $from, $to }) => {
1167
+ const from = $from.pos;
1168
+ const to = $to.pos;
1169
+ state.doc.nodesBetween(from, to, (node, pos) => {
1170
+ if (!node.isText && !node.marks.length) {
1171
+ return;
1172
+ }
1173
+ const relativeFrom = Math.max(from, pos);
1174
+ const relativeTo = Math.min(to, pos + node.nodeSize);
1175
+ const range2 = relativeTo - relativeFrom;
1176
+ selectionRange += range2;
1177
+ markRanges.push(...node.marks.map((mark) => ({
1178
+ mark,
1179
+ from: relativeFrom,
1180
+ to: relativeTo
1181
+ })));
1182
+ });
1183
+ });
1184
+ if (selectionRange === 0) {
1185
+ return false;
1186
+ }
1187
+ const matchedRange = markRanges.filter((markRange) => {
1188
+ if (!type) {
1189
+ return true;
1190
+ }
1191
+ return type.name === markRange.mark.type.name;
1192
+ }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
1193
+ const excludedRange = markRanges.filter((markRange) => {
1194
+ if (!type) {
1195
+ return true;
1196
+ }
1197
+ return markRange.mark.type !== type && markRange.mark.type.excludes(type);
1198
+ }).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
1199
+ const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange;
1200
+ return range >= selectionRange;
1201
+ }
1202
+ function isList(name, extensions) {
1203
+ const { nodeExtensions } = splitExtensions(extensions);
1204
+ const extension = nodeExtensions.find((item) => item.name === name);
1205
+ if (!extension) {
1206
+ return false;
1207
+ }
1208
+ const context = {
1209
+ name: extension.name,
1210
+ options: extension.options,
1211
+ storage: extension.storage
1212
+ };
1213
+ const group = callOrReturn(getExtensionField(extension, "group", context));
1214
+ if (typeof group !== "string") {
1215
+ return false;
1216
+ }
1217
+ return group.split(" ").includes("list");
1218
+ }
1219
+ function isNodeEmpty(node, { checkChildren = true, ignoreWhitespace = false } = {}) {
1220
+ var _a;
1221
+ if (ignoreWhitespace) {
1222
+ if (node.type.name === "hardBreak") {
1223
+ return true;
1224
+ }
1225
+ if (node.isText) {
1226
+ return /^\s*$/m.test((_a = node.text) !== null && _a !== void 0 ? _a : "");
1227
+ }
1228
+ }
1229
+ if (node.isText) {
1230
+ return !node.text;
1231
+ }
1232
+ if (node.isAtom || node.isLeaf) {
1233
+ return false;
1234
+ }
1235
+ if (node.content.childCount === 0) {
1236
+ return true;
1237
+ }
1238
+ if (checkChildren) {
1239
+ let isContentEmpty = true;
1240
+ node.content.forEach((childNode) => {
1241
+ if (isContentEmpty === false) {
1242
+ return;
1243
+ }
1244
+ if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {
1245
+ isContentEmpty = false;
1246
+ }
1247
+ });
1248
+ return isContentEmpty;
1249
+ }
1250
+ return false;
1251
+ }
1252
+ function canSetMark(state, tr, newMarkType) {
1253
+ var _a;
1254
+ const { selection } = tr;
1255
+ let cursor = null;
1256
+ if (isTextSelection(selection)) {
1257
+ cursor = selection.$cursor;
1258
+ }
1259
+ if (cursor) {
1260
+ const currentMarks = (_a = state.storedMarks) !== null && _a !== void 0 ? _a : cursor.marks();
1261
+ return !!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark) => mark.type.excludes(newMarkType));
1262
+ }
1263
+ const { ranges } = selection;
1264
+ return ranges.some(({ $from, $to }) => {
1265
+ let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false;
1266
+ state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => {
1267
+ if (someNodeSupportsMark) {
1268
+ return false;
1269
+ }
1270
+ if (node.isInline) {
1271
+ const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType);
1272
+ const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks) || !node.marks.some((otherMark) => otherMark.type.excludes(newMarkType));
1273
+ someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType;
1274
+ }
1275
+ return !someNodeSupportsMark;
1276
+ });
1277
+ return someNodeSupportsMark;
1278
+ });
1279
+ }
1280
+ var setMark = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
1281
+ const { selection } = tr;
1282
+ const { empty, ranges } = selection;
1283
+ const type = getMarkType(typeOrName, state.schema);
1284
+ if (dispatch) {
1285
+ if (empty) {
1286
+ const oldAttributes = getMarkAttributes(state, type);
1287
+ tr.addStoredMark(type.create({
1288
+ ...oldAttributes,
1289
+ ...attributes
1290
+ }));
1291
+ } else {
1292
+ ranges.forEach((range) => {
1293
+ const from = range.$from.pos;
1294
+ const to = range.$to.pos;
1295
+ state.doc.nodesBetween(from, to, (node, pos) => {
1296
+ const trimmedFrom = Math.max(pos, from);
1297
+ const trimmedTo = Math.min(pos + node.nodeSize, to);
1298
+ const someHasMark = node.marks.find((mark) => mark.type === type);
1299
+ if (someHasMark) {
1300
+ node.marks.forEach((mark) => {
1301
+ if (type === mark.type) {
1302
+ tr.addMark(trimmedFrom, trimmedTo, type.create({
1303
+ ...mark.attrs,
1304
+ ...attributes
1305
+ }));
1306
+ }
1307
+ });
1308
+ } else {
1309
+ tr.addMark(trimmedFrom, trimmedTo, type.create(attributes));
1310
+ }
1311
+ });
1312
+ });
1313
+ }
1314
+ }
1315
+ return canSetMark(state, tr, type);
1316
+ };
1317
+ var setMeta = (key, value) => ({ tr }) => {
1318
+ tr.setMeta(key, value);
1319
+ return true;
1320
+ };
1321
+ var setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => {
1322
+ const type = getNodeType(typeOrName, state.schema);
1323
+ let attributesToCopy;
1324
+ if (state.selection.$anchor.sameParent(state.selection.$head)) {
1325
+ attributesToCopy = state.selection.$anchor.parent.attrs;
1326
+ }
1327
+ if (!type.isTextblock) {
1328
+ console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.');
1329
+ return false;
1330
+ }
1331
+ return chain().command(({ commands: commands2 }) => {
1332
+ const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state);
1333
+ if (canSetBlock) {
1334
+ return true;
1335
+ }
1336
+ return commands2.clearNodes();
1337
+ }).command(({ state: updatedState }) => {
1338
+ return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch);
1339
+ }).run();
1340
+ };
1341
+ var setNodeSelection = (position) => ({ tr, dispatch }) => {
1342
+ if (dispatch) {
1343
+ const { doc } = tr;
1344
+ const from = minMax(position, 0, doc.content.size);
1345
+ const selection = NodeSelection.create(doc, from);
1346
+ tr.setSelection(selection);
1347
+ }
1348
+ return true;
1349
+ };
1350
+ var setTextSelection = (position) => ({ tr, dispatch }) => {
1351
+ if (dispatch) {
1352
+ const { doc } = tr;
1353
+ const { from, to } = typeof position === "number" ? { from: position, to: position } : position;
1354
+ const minPos = TextSelection.atStart(doc).from;
1355
+ const maxPos = TextSelection.atEnd(doc).to;
1356
+ const resolvedFrom = minMax(from, minPos, maxPos);
1357
+ const resolvedEnd = minMax(to, minPos, maxPos);
1358
+ const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd);
1359
+ tr.setSelection(selection);
1360
+ }
1361
+ return true;
1362
+ };
1363
+ var sinkListItem = (typeOrName) => ({ state, dispatch }) => {
1364
+ const type = getNodeType(typeOrName, state.schema);
1365
+ return sinkListItem$1(type)(state, dispatch);
1366
+ };
1367
+ function ensureMarks(state, splittableMarks) {
1368
+ const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();
1369
+ if (marks) {
1370
+ const filteredMarks = marks.filter((mark) => splittableMarks === null || splittableMarks === void 0 ? void 0 : splittableMarks.includes(mark.type.name));
1371
+ state.tr.ensureMarks(filteredMarks);
1372
+ }
1373
+ }
1374
+ var splitBlock = ({ keepMarks = true } = {}) => ({ tr, state, dispatch, editor }) => {
1375
+ const { selection, doc } = tr;
1376
+ const { $from, $to } = selection;
1377
+ const extensionAttributes = editor.extensionManager.attributes;
1378
+ const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);
1379
+ if (selection instanceof NodeSelection && selection.node.isBlock) {
1380
+ if (!$from.parentOffset || !canSplit(doc, $from.pos)) {
1381
+ return false;
1382
+ }
1383
+ if (dispatch) {
1384
+ if (keepMarks) {
1385
+ ensureMarks(state, editor.extensionManager.splittableMarks);
1386
+ }
1387
+ tr.split($from.pos).scrollIntoView();
1388
+ }
1389
+ return true;
1390
+ }
1391
+ if (!$from.parent.isBlock) {
1392
+ return false;
1393
+ }
1394
+ const atEnd = $to.parentOffset === $to.parent.content.size;
1395
+ const deflt = $from.depth === 0 ? void 0 : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));
1396
+ let types = atEnd && deflt ? [
1397
+ {
1398
+ type: deflt,
1399
+ attrs: newAttributes
1400
+ }
1401
+ ] : void 0;
1402
+ let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types);
1403
+ if (!types && !can && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) {
1404
+ can = true;
1405
+ types = deflt ? [
1406
+ {
1407
+ type: deflt,
1408
+ attrs: newAttributes
1409
+ }
1410
+ ] : void 0;
1411
+ }
1412
+ if (dispatch) {
1413
+ if (can) {
1414
+ if (selection instanceof TextSelection) {
1415
+ tr.deleteSelection();
1416
+ }
1417
+ tr.split(tr.mapping.map($from.pos), 1, types);
1418
+ if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {
1419
+ const first2 = tr.mapping.map($from.before());
1420
+ const $first = tr.doc.resolve(first2);
1421
+ if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {
1422
+ tr.setNodeMarkup(tr.mapping.map($from.before()), deflt);
1423
+ }
1424
+ }
1425
+ }
1426
+ if (keepMarks) {
1427
+ ensureMarks(state, editor.extensionManager.splittableMarks);
1428
+ }
1429
+ tr.scrollIntoView();
1430
+ }
1431
+ return can;
1432
+ };
1433
+ var splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr, state, dispatch, editor }) => {
1434
+ var _a;
1435
+ const type = getNodeType(typeOrName, state.schema);
1436
+ const { $from, $to } = state.selection;
1437
+ const node = state.selection.node;
1438
+ if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) {
1439
+ return false;
1440
+ }
1441
+ const grandParent = $from.node(-1);
1442
+ if (grandParent.type !== type) {
1443
+ return false;
1444
+ }
1445
+ const extensionAttributes = editor.extensionManager.attributes;
1446
+ if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {
1447
+ if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) {
1448
+ return false;
1449
+ }
1450
+ if (dispatch) {
1451
+ let wrap = Fragment.empty;
1452
+ const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;
1453
+ for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {
1454
+ wrap = Fragment.from($from.node(d).copy(wrap));
1455
+ }
1456
+ const depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3;
1457
+ const newNextTypeAttributes2 = {
1458
+ ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
1459
+ ...overrideAttrs
1460
+ };
1461
+ const nextType2 = ((_a = type.contentMatch.defaultType) === null || _a === void 0 ? void 0 : _a.createAndFill(newNextTypeAttributes2)) || void 0;
1462
+ wrap = wrap.append(Fragment.from(type.createAndFill(null, nextType2) || void 0));
1463
+ const start = $from.before($from.depth - (depthBefore - 1));
1464
+ tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0));
1465
+ let sel = -1;
1466
+ tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {
1467
+ if (sel > -1) {
1468
+ return false;
1469
+ }
1470
+ if (n.isTextblock && n.content.size === 0) {
1471
+ sel = pos + 1;
1472
+ }
1473
+ });
1474
+ if (sel > -1) {
1475
+ tr.setSelection(TextSelection.near(tr.doc.resolve(sel)));
1476
+ }
1477
+ tr.scrollIntoView();
1478
+ }
1479
+ return true;
1480
+ }
1481
+ const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
1482
+ const newTypeAttributes = {
1483
+ ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),
1484
+ ...overrideAttrs
1485
+ };
1486
+ const newNextTypeAttributes = {
1487
+ ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
1488
+ ...overrideAttrs
1489
+ };
1490
+ tr.delete($from.pos, $to.pos);
1491
+ const types = nextType ? [
1492
+ { type, attrs: newTypeAttributes },
1493
+ { type: nextType, attrs: newNextTypeAttributes }
1494
+ ] : [{ type, attrs: newTypeAttributes }];
1495
+ if (!canSplit(tr.doc, $from.pos, 2)) {
1496
+ return false;
1497
+ }
1498
+ if (dispatch) {
1499
+ const { selection, storedMarks } = state;
1500
+ const { splittableMarks } = editor.extensionManager;
1501
+ const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
1502
+ tr.split($from.pos, 2, types).scrollIntoView();
1503
+ if (!marks || !dispatch) {
1504
+ return true;
1505
+ }
1506
+ const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
1507
+ tr.ensureMarks(filteredMarks);
1508
+ }
1509
+ return true;
1510
+ };
1511
+ var joinListBackwards = (tr, listType) => {
1512
+ const list = findParentNode((node) => node.type === listType)(tr.selection);
1513
+ if (!list) {
1514
+ return true;
1515
+ }
1516
+ const before = tr.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth);
1517
+ if (before === void 0) {
1518
+ return true;
1519
+ }
1520
+ const nodeBefore = tr.doc.nodeAt(before);
1521
+ const canJoinBackwards = list.node.type === (nodeBefore === null || nodeBefore === void 0 ? void 0 : nodeBefore.type) && canJoin(tr.doc, list.pos);
1522
+ if (!canJoinBackwards) {
1523
+ return true;
1524
+ }
1525
+ tr.join(list.pos);
1526
+ return true;
1527
+ };
1528
+ var joinListForwards = (tr, listType) => {
1529
+ const list = findParentNode((node) => node.type === listType)(tr.selection);
1530
+ if (!list) {
1531
+ return true;
1532
+ }
1533
+ const after = tr.doc.resolve(list.start).after(list.depth);
1534
+ if (after === void 0) {
1535
+ return true;
1536
+ }
1537
+ const nodeAfter = tr.doc.nodeAt(after);
1538
+ const canJoinForwards = list.node.type === (nodeAfter === null || nodeAfter === void 0 ? void 0 : nodeAfter.type) && canJoin(tr.doc, after);
1539
+ if (!canJoinForwards) {
1540
+ return true;
1541
+ }
1542
+ tr.join(after);
1543
+ return true;
1544
+ };
1545
+ var toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr, state, dispatch, chain, commands: commands2, can }) => {
1546
+ const { extensions, splittableMarks } = editor.extensionManager;
1547
+ const listType = getNodeType(listTypeOrName, state.schema);
1548
+ const itemType = getNodeType(itemTypeOrName, state.schema);
1549
+ const { selection, storedMarks } = state;
1550
+ const { $from, $to } = selection;
1551
+ const range = $from.blockRange($to);
1552
+ const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
1553
+ if (!range) {
1554
+ return false;
1555
+ }
1556
+ const parentList = findParentNode((node) => isList(node.type.name, extensions))(selection);
1557
+ if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {
1558
+ if (parentList.node.type === listType) {
1559
+ return commands2.liftListItem(itemType);
1560
+ }
1561
+ if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content) && dispatch) {
1562
+ return chain().command(() => {
1563
+ tr.setNodeMarkup(parentList.pos, listType);
1564
+ return true;
1565
+ }).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
1566
+ }
1567
+ }
1568
+ if (!keepMarks || !marks || !dispatch) {
1569
+ return chain().command(() => {
1570
+ const canWrapInList = can().wrapInList(listType, attributes);
1571
+ if (canWrapInList) {
1572
+ return true;
1573
+ }
1574
+ return commands2.clearNodes();
1575
+ }).wrapInList(listType, attributes).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
1576
+ }
1577
+ return chain().command(() => {
1578
+ const canWrapInList = can().wrapInList(listType, attributes);
1579
+ const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
1580
+ tr.ensureMarks(filteredMarks);
1581
+ if (canWrapInList) {
1582
+ return true;
1583
+ }
1584
+ return commands2.clearNodes();
1585
+ }).wrapInList(listType, attributes).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
1586
+ };
1587
+ var toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands: commands2 }) => {
1588
+ const { extendEmptyMarkRange = false } = options;
1589
+ const type = getMarkType(typeOrName, state.schema);
1590
+ const isActive = isMarkActive(state, type, attributes);
1591
+ if (isActive) {
1592
+ return commands2.unsetMark(type, { extendEmptyMarkRange });
1593
+ }
1594
+ return commands2.setMark(type, attributes);
1595
+ };
1596
+ var toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands: commands2 }) => {
1597
+ const type = getNodeType(typeOrName, state.schema);
1598
+ const toggleType = getNodeType(toggleTypeOrName, state.schema);
1599
+ const isActive = isNodeActive(state, type, attributes);
1600
+ let attributesToCopy;
1601
+ if (state.selection.$anchor.sameParent(state.selection.$head)) {
1602
+ attributesToCopy = state.selection.$anchor.parent.attrs;
1603
+ }
1604
+ if (isActive) {
1605
+ return commands2.setNode(toggleType, attributesToCopy);
1606
+ }
1607
+ return commands2.setNode(type, { ...attributesToCopy, ...attributes });
1608
+ };
1609
+ var toggleWrap = (typeOrName, attributes = {}) => ({ state, commands: commands2 }) => {
1610
+ const type = getNodeType(typeOrName, state.schema);
1611
+ const isActive = isNodeActive(state, type, attributes);
1612
+ if (isActive) {
1613
+ return commands2.lift(type);
1614
+ }
1615
+ return commands2.wrapIn(type, attributes);
1616
+ };
1617
+ var undoInputRule = () => ({ state, dispatch }) => {
1618
+ const plugins = state.plugins;
1619
+ for (let i = 0; i < plugins.length; i += 1) {
1620
+ const plugin = plugins[i];
1621
+ let undoable;
1622
+ if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
1623
+ if (dispatch) {
1624
+ const tr = state.tr;
1625
+ const toUndo = undoable.transform;
1626
+ for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {
1627
+ tr.step(toUndo.steps[j].invert(toUndo.docs[j]));
1628
+ }
1629
+ if (undoable.text) {
1630
+ const marks = tr.doc.resolve(undoable.from).marks();
1631
+ tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));
1632
+ } else {
1633
+ tr.delete(undoable.from, undoable.to);
1634
+ }
1635
+ }
1636
+ return true;
1637
+ }
1638
+ }
1639
+ return false;
1640
+ };
1641
+ var unsetAllMarks = () => ({ tr, dispatch }) => {
1642
+ const { selection } = tr;
1643
+ const { empty, ranges } = selection;
1644
+ if (empty) {
1645
+ return true;
1646
+ }
1647
+ if (dispatch) {
1648
+ ranges.forEach((range) => {
1649
+ tr.removeMark(range.$from.pos, range.$to.pos);
1650
+ });
1651
+ }
1652
+ return true;
1653
+ };
1654
+ var unsetMark = (typeOrName, options = {}) => ({ tr, state, dispatch }) => {
1655
+ var _a;
1656
+ const { extendEmptyMarkRange = false } = options;
1657
+ const { selection } = tr;
1658
+ const type = getMarkType(typeOrName, state.schema);
1659
+ const { $from, empty, ranges } = selection;
1660
+ if (!dispatch) {
1661
+ return true;
1662
+ }
1663
+ if (empty && extendEmptyMarkRange) {
1664
+ let { from, to } = selection;
1665
+ const attrs = (_a = $from.marks().find((mark) => mark.type === type)) === null || _a === void 0 ? void 0 : _a.attrs;
1666
+ const range = getMarkRange($from, type, attrs);
1667
+ if (range) {
1668
+ from = range.from;
1669
+ to = range.to;
1670
+ }
1671
+ tr.removeMark(from, to, type);
1672
+ } else {
1673
+ ranges.forEach((range) => {
1674
+ tr.removeMark(range.$from.pos, range.$to.pos, type);
1675
+ });
1676
+ }
1677
+ tr.removeStoredMark(type);
1678
+ return true;
1679
+ };
1680
+ var updateAttributes = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
1681
+ let nodeType = null;
1682
+ let markType = null;
1683
+ const schemaType = getSchemaTypeNameByName(typeof typeOrName === "string" ? typeOrName : typeOrName.name, state.schema);
1684
+ if (!schemaType) {
1685
+ return false;
1686
+ }
1687
+ if (schemaType === "node") {
1688
+ nodeType = getNodeType(typeOrName, state.schema);
1689
+ }
1690
+ if (schemaType === "mark") {
1691
+ markType = getMarkType(typeOrName, state.schema);
1692
+ }
1693
+ if (dispatch) {
1694
+ tr.selection.ranges.forEach((range) => {
1695
+ const from = range.$from.pos;
1696
+ const to = range.$to.pos;
1697
+ let lastPos;
1698
+ let lastNode;
1699
+ let trimmedFrom;
1700
+ let trimmedTo;
1701
+ if (tr.selection.empty) {
1702
+ state.doc.nodesBetween(from, to, (node, pos) => {
1703
+ if (nodeType && nodeType === node.type) {
1704
+ trimmedFrom = Math.max(pos, from);
1705
+ trimmedTo = Math.min(pos + node.nodeSize, to);
1706
+ lastPos = pos;
1707
+ lastNode = node;
1708
+ }
1709
+ });
1710
+ } else {
1711
+ state.doc.nodesBetween(from, to, (node, pos) => {
1712
+ if (pos < from && nodeType && nodeType === node.type) {
1713
+ trimmedFrom = Math.max(pos, from);
1714
+ trimmedTo = Math.min(pos + node.nodeSize, to);
1715
+ lastPos = pos;
1716
+ lastNode = node;
1717
+ }
1718
+ if (pos >= from && pos <= to) {
1719
+ if (nodeType && nodeType === node.type) {
1720
+ tr.setNodeMarkup(pos, void 0, {
1721
+ ...node.attrs,
1722
+ ...attributes
1723
+ });
1724
+ }
1725
+ if (markType && node.marks.length) {
1726
+ node.marks.forEach((mark) => {
1727
+ if (markType === mark.type) {
1728
+ const trimmedFrom2 = Math.max(pos, from);
1729
+ const trimmedTo2 = Math.min(pos + node.nodeSize, to);
1730
+ tr.addMark(trimmedFrom2, trimmedTo2, markType.create({
1731
+ ...mark.attrs,
1732
+ ...attributes
1733
+ }));
1734
+ }
1735
+ });
1736
+ }
1737
+ }
1738
+ });
1739
+ }
1740
+ if (lastNode) {
1741
+ if (lastPos !== void 0) {
1742
+ tr.setNodeMarkup(lastPos, void 0, {
1743
+ ...lastNode.attrs,
1744
+ ...attributes
1745
+ });
1746
+ }
1747
+ if (markType && lastNode.marks.length) {
1748
+ lastNode.marks.forEach((mark) => {
1749
+ if (markType === mark.type) {
1750
+ tr.addMark(trimmedFrom, trimmedTo, markType.create({
1751
+ ...mark.attrs,
1752
+ ...attributes
1753
+ }));
1754
+ }
1755
+ });
1756
+ }
1757
+ }
1758
+ });
1759
+ }
1760
+ return true;
1761
+ };
1762
+ var wrapIn = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
1763
+ const type = getNodeType(typeOrName, state.schema);
1764
+ return wrapIn$1(type, attributes)(state, dispatch);
1765
+ };
1766
+ var wrapInList = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
1767
+ const type = getNodeType(typeOrName, state.schema);
1768
+ return wrapInList$1(type, attributes)(state, dispatch);
1769
+ };
1770
+ var commands = /* @__PURE__ */ Object.freeze({
1771
+ __proto__: null,
1772
+ blur,
1773
+ clearContent,
1774
+ clearNodes,
1775
+ command,
1776
+ createParagraphNear,
1777
+ cut,
1778
+ deleteCurrentNode,
1779
+ deleteNode,
1780
+ deleteRange,
1781
+ deleteSelection,
1782
+ enter,
1783
+ exitCode,
1784
+ extendMarkRange,
1785
+ first,
1786
+ focus,
1787
+ forEach,
1788
+ insertContent,
1789
+ insertContentAt,
1790
+ joinBackward,
1791
+ joinDown,
1792
+ joinForward,
1793
+ joinItemBackward,
1794
+ joinItemForward,
1795
+ joinTextblockBackward,
1796
+ joinTextblockForward,
1797
+ joinUp,
1798
+ keyboardShortcut,
1799
+ lift,
1800
+ liftEmptyBlock,
1801
+ liftListItem,
1802
+ newlineInCode,
1803
+ resetAttributes,
1804
+ scrollIntoView,
1805
+ selectAll,
1806
+ selectNodeBackward,
1807
+ selectNodeForward,
1808
+ selectParentNode,
1809
+ selectTextblockEnd,
1810
+ selectTextblockStart,
1811
+ setContent,
1812
+ setMark,
1813
+ setMeta,
1814
+ setNode,
1815
+ setNodeSelection,
1816
+ setTextSelection,
1817
+ sinkListItem,
1818
+ splitBlock,
1819
+ splitListItem,
1820
+ toggleList,
1821
+ toggleMark,
1822
+ toggleNode,
1823
+ toggleWrap,
1824
+ undoInputRule,
1825
+ unsetAllMarks,
1826
+ unsetMark,
1827
+ updateAttributes,
1828
+ wrapIn,
1829
+ wrapInList
1830
+ });
1831
+ var Commands = Extension.create({
1832
+ name: "commands",
1833
+ addCommands() {
1834
+ return {
1835
+ ...commands
1836
+ };
1837
+ }
1838
+ });
1839
+ var Drop = Extension.create({
1840
+ name: "drop",
1841
+ addProseMirrorPlugins() {
1842
+ return [
1843
+ new Plugin({
1844
+ key: new PluginKey("tiptapDrop"),
1845
+ props: {
1846
+ handleDrop: (_, e, slice, moved) => {
1847
+ this.editor.emit("drop", {
1848
+ editor: this.editor,
1849
+ event: e,
1850
+ slice,
1851
+ moved
1852
+ });
1853
+ }
1854
+ }
1855
+ })
1856
+ ];
1857
+ }
1858
+ });
1859
+ var Editable = Extension.create({
1860
+ name: "editable",
1861
+ addProseMirrorPlugins() {
1862
+ return [
1863
+ new Plugin({
1864
+ key: new PluginKey("editable"),
1865
+ props: {
1866
+ editable: () => this.editor.options.editable
1867
+ }
1868
+ })
1869
+ ];
1870
+ }
1871
+ });
1872
+ var focusEventsPluginKey = new PluginKey("focusEvents");
1873
+ var FocusEvents = Extension.create({
1874
+ name: "focusEvents",
1875
+ addProseMirrorPlugins() {
1876
+ const { editor } = this;
1877
+ return [
1878
+ new Plugin({
1879
+ key: focusEventsPluginKey,
1880
+ props: {
1881
+ handleDOMEvents: {
1882
+ focus: (view, event) => {
1883
+ editor.isFocused = true;
1884
+ const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false);
1885
+ view.dispatch(transaction);
1886
+ return false;
1887
+ },
1888
+ blur: (view, event) => {
1889
+ editor.isFocused = false;
1890
+ const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false);
1891
+ view.dispatch(transaction);
1892
+ return false;
1893
+ }
1894
+ }
1895
+ }
1896
+ })
1897
+ ];
1898
+ }
1899
+ });
1900
+ var Keymap = Extension.create({
1901
+ name: "keymap",
1902
+ addKeyboardShortcuts() {
1903
+ const handleBackspace = () => this.editor.commands.first(({ commands: commands2 }) => [
1904
+ () => commands2.undoInputRule(),
1905
+ // maybe convert first text block node to default node
1906
+ () => commands2.command(({ tr }) => {
1907
+ const { selection, doc } = tr;
1908
+ const { empty, $anchor } = selection;
1909
+ const { pos, parent } = $anchor;
1910
+ const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr.doc.resolve(pos - 1) : $anchor;
1911
+ const parentIsIsolating = $parentPos.parent.type.spec.isolating;
1912
+ const parentPos = $anchor.pos - $anchor.parentOffset;
1913
+ const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : Selection.atStart(doc).from === pos;
1914
+ if (!empty || !parent.type.isTextblock || parent.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") {
1915
+ return false;
1916
+ }
1917
+ return commands2.clearNodes();
1918
+ }),
1919
+ () => commands2.deleteSelection(),
1920
+ () => commands2.joinBackward(),
1921
+ () => commands2.selectNodeBackward()
1922
+ ]);
1923
+ const handleDelete = () => this.editor.commands.first(({ commands: commands2 }) => [
1924
+ () => commands2.deleteSelection(),
1925
+ () => commands2.deleteCurrentNode(),
1926
+ () => commands2.joinForward(),
1927
+ () => commands2.selectNodeForward()
1928
+ ]);
1929
+ const handleEnter = () => this.editor.commands.first(({ commands: commands2 }) => [
1930
+ () => commands2.newlineInCode(),
1931
+ () => commands2.createParagraphNear(),
1932
+ () => commands2.liftEmptyBlock(),
1933
+ () => commands2.splitBlock()
1934
+ ]);
1935
+ const baseKeymap = {
1936
+ Enter: handleEnter,
1937
+ "Mod-Enter": () => this.editor.commands.exitCode(),
1938
+ Backspace: handleBackspace,
1939
+ "Mod-Backspace": handleBackspace,
1940
+ "Shift-Backspace": handleBackspace,
1941
+ Delete: handleDelete,
1942
+ "Mod-Delete": handleDelete,
1943
+ "Mod-a": () => this.editor.commands.selectAll()
1944
+ };
1945
+ const pcKeymap = {
1946
+ ...baseKeymap
1947
+ };
1948
+ const macKeymap = {
1949
+ ...baseKeymap,
1950
+ "Ctrl-h": handleBackspace,
1951
+ "Alt-Backspace": handleBackspace,
1952
+ "Ctrl-d": handleDelete,
1953
+ "Ctrl-Alt-Backspace": handleDelete,
1954
+ "Alt-Delete": handleDelete,
1955
+ "Alt-d": handleDelete,
1956
+ "Ctrl-a": () => this.editor.commands.selectTextblockStart(),
1957
+ "Ctrl-e": () => this.editor.commands.selectTextblockEnd()
1958
+ };
1959
+ if (isiOS() || isMacOS()) {
1960
+ return macKeymap;
1961
+ }
1962
+ return pcKeymap;
1963
+ },
1964
+ addProseMirrorPlugins() {
1965
+ return [
1966
+ // With this plugin we check if the whole document was selected and deleted.
1967
+ // In this case we will additionally call `clearNodes()` to convert e.g. a heading
1968
+ // to a paragraph if necessary.
1969
+ // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well
1970
+ // with many other commands.
1971
+ new Plugin({
1972
+ key: new PluginKey("clearDocument"),
1973
+ appendTransaction: (transactions, oldState, newState) => {
1974
+ if (transactions.some((tr2) => tr2.getMeta("composition"))) {
1975
+ return;
1976
+ }
1977
+ const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc);
1978
+ const ignoreTr = transactions.some((transaction) => transaction.getMeta("preventClearDocument"));
1979
+ if (!docChanges || ignoreTr) {
1980
+ return;
1981
+ }
1982
+ const { empty, from, to } = oldState.selection;
1983
+ const allFrom = Selection.atStart(oldState.doc).from;
1984
+ const allEnd = Selection.atEnd(oldState.doc).to;
1985
+ const allWasSelected = from === allFrom && to === allEnd;
1986
+ if (empty || !allWasSelected) {
1987
+ return;
1988
+ }
1989
+ const isEmpty = isNodeEmpty(newState.doc);
1990
+ if (!isEmpty) {
1991
+ return;
1992
+ }
1993
+ const tr = newState.tr;
1994
+ const state = createChainableState({
1995
+ state: newState,
1996
+ transaction: tr
1997
+ });
1998
+ const { commands: commands2 } = new CommandManager({
1999
+ editor: this.editor,
2000
+ state
2001
+ });
2002
+ commands2.clearNodes();
2003
+ if (!tr.steps.length) {
2004
+ return;
2005
+ }
2006
+ return tr;
2007
+ }
2008
+ })
2009
+ ];
2010
+ }
2011
+ });
2012
+ var Paste = Extension.create({
2013
+ name: "paste",
2014
+ addProseMirrorPlugins() {
2015
+ return [
2016
+ new Plugin({
2017
+ key: new PluginKey("tiptapPaste"),
2018
+ props: {
2019
+ handlePaste: (_view, e, slice) => {
2020
+ this.editor.emit("paste", {
2021
+ editor: this.editor,
2022
+ event: e,
2023
+ slice
2024
+ });
2025
+ }
2026
+ }
2027
+ })
2028
+ ];
2029
+ }
2030
+ });
2031
+ var Tabindex = Extension.create({
2032
+ name: "tabindex",
2033
+ addProseMirrorPlugins() {
2034
+ return [
2035
+ new Plugin({
2036
+ key: new PluginKey("tabindex"),
2037
+ props: {
2038
+ attributes: () => this.editor.isEditable ? { tabindex: "0" } : {}
2039
+ }
2040
+ })
2041
+ ];
2042
+ }
2043
+ });
2044
+
2045
+ // src/extensions/PageLayout.ts
2046
+ import { Plugin as Plugin2, PluginKey as PluginKey2 } from "@tiptap/pm/state";
2047
+ import { Decoration, DecorationSet } from "@tiptap/pm/view";
2048
+
2049
+ // src/types.ts
2050
+ var PAGE_DIMENSIONS = {
2051
+ A4: {
2052
+ widthMm: 210,
2053
+ heightMm: 297,
2054
+ paddingTopMm: 22,
2055
+ paddingBottomMm: 22,
2056
+ paddingLeftMm: 28,
2057
+ paddingRightMm: 28
2058
+ },
2059
+ Letter: {
2060
+ widthMm: 216,
2061
+ heightMm: 279,
2062
+ paddingTopMm: 22,
2063
+ paddingBottomMm: 22,
2064
+ paddingLeftMm: 28,
2065
+ paddingRightMm: 28
2066
+ }
2067
+ };
2068
+ var PX_PER_MM = 3.7795;
2069
+ function getBodyHeightPx(size) {
2070
+ const d = PAGE_DIMENSIONS[size];
2071
+ return Math.round((d.heightMm - d.paddingTopMm - d.paddingBottomMm) * PX_PER_MM);
2072
+ }
2073
+ function getBodyWidthPx(size) {
2074
+ const d = PAGE_DIMENSIONS[size];
2075
+ return Math.round((d.widthMm - d.paddingLeftMm - d.paddingRightMm) * PX_PER_MM);
2076
+ }
2077
+ function getPageWidthPx(size) {
2078
+ const d = PAGE_DIMENSIONS[size];
2079
+ return Math.round(d.widthMm * PX_PER_MM);
2080
+ }
2081
+ var PARCHMENT_DEFAULTS = {
2082
+ canvasBg: "#e0ddd4",
2083
+ paperColor: "#f5f4ed",
2084
+ textColor: "#141413",
2085
+ lineColor: "#c8c4b8",
2086
+ accentColor: "#1b365d"
2087
+ };
2088
+ var MINIMAL_DEFAULTS = {
2089
+ canvasBg: "#e8e8e8",
2090
+ paperColor: "#ffffff",
2091
+ textColor: "#111111",
2092
+ lineColor: "#d0d0d0",
2093
+ accentColor: "#2563eb"
2094
+ };
2095
+
2096
+ // src/extensions/PageLayout.ts
2097
+ var META_KEY = "pageBreakDecos";
2098
+ var pluginKey = new PluginKey2("pageBreak");
2099
+ function makeGapWidget(gapHeightPx, pageIndex) {
2100
+ const el = document.createElement("div");
2101
+ el.className = "ink-page-gap";
2102
+ el.setAttribute("data-page-gap", String(pageIndex));
2103
+ el.style.height = `${gapHeightPx}px`;
2104
+ el.contentEditable = "false";
2105
+ return el;
2106
+ }
2107
+ function computeDecorations(doc, view, bodyHeightPx, gapHeightPx) {
2108
+ const decorations = [];
2109
+ let pageIndex = 1;
2110
+ let baseY = null;
2111
+ doc.descendants((node, pos) => {
2112
+ if (!node.isBlock) return;
2113
+ const insidePos = pos + 1;
2114
+ if (insidePos >= doc.content.size) return;
2115
+ let top;
2116
+ let bottom;
2117
+ try {
2118
+ top = view.coordsAtPos(insidePos).top;
2119
+ const endPos = pos + node.nodeSize - 1;
2120
+ bottom = endPos > insidePos ? view.coordsAtPos(endPos).bottom : top + 28;
2121
+ } catch {
2122
+ return;
2123
+ }
2124
+ if (baseY === null) baseY = top;
2125
+ const threshold = pageIndex * bodyHeightPx + (pageIndex - 1) * gapHeightPx;
2126
+ const relTop = top - baseY;
2127
+ const relBottom = bottom - baseY;
2128
+ if (relTop >= threshold || relBottom > threshold && relTop < threshold) {
2129
+ const idx = pageIndex;
2130
+ decorations.push(
2131
+ Decoration.widget(pos, () => makeGapWidget(gapHeightPx, idx), {
2132
+ side: -1,
2133
+ key: `page-gap-${idx}`
2134
+ })
2135
+ );
2136
+ pageIndex++;
2137
+ }
2138
+ });
2139
+ return DecorationSet.create(doc, decorations);
2140
+ }
2141
+ function measurePageDimensions(view, pageSize) {
2142
+ const card = view.dom.closest(".ink-page-card");
2143
+ if (!card) return null;
2144
+ const style = window.getComputedStyle(card);
2145
+ const paddingTop = parseFloat(style.paddingTop);
2146
+ const paddingBottom = parseFloat(style.paddingBottom);
2147
+ const gapHeightPx = Math.round(paddingTop + paddingBottom);
2148
+ const dims = PAGE_DIMENSIONS[pageSize];
2149
+ const bodyMm = dims.heightMm - dims.paddingTopMm - dims.paddingBottomMm;
2150
+ const gapMm = dims.paddingTopMm + dims.paddingBottomMm;
2151
+ const pmPaddingTop = parseFloat(window.getComputedStyle(view.dom).paddingTop) || 28;
2152
+ const rawWidgetHeight = gapHeightPx - pmPaddingTop;
2153
+ const widgetHeightPx = Math.round(rawWidgetHeight / 28) * 28;
2154
+ const rawBodyHeight = Math.round(bodyMm / gapMm * gapHeightPx);
2155
+ const bodyHeightPx = Math.floor(rawBodyHeight / 28) * 28;
2156
+ return { bodyHeightPx, gapHeightPx: widgetHeightPx };
2157
+ }
2158
+ function buildPageBreakPlugin(pageSize) {
2159
+ let rafId = null;
2160
+ function scheduleUpdate(view) {
2161
+ if (rafId !== null) cancelAnimationFrame(rafId);
2162
+ rafId = requestAnimationFrame(() => {
2163
+ rafId = null;
2164
+ if (view.isDestroyed) return;
2165
+ const dims = measurePageDimensions(view, pageSize);
2166
+ if (!dims) return;
2167
+ const { bodyHeightPx, gapHeightPx } = dims;
2168
+ const decos = computeDecorations(view.state.doc, view, bodyHeightPx, gapHeightPx);
2169
+ const tr = view.state.tr.setMeta(META_KEY, decos);
2170
+ tr.setMeta("addToHistory", false);
2171
+ view.dispatch(tr);
2172
+ });
2173
+ }
2174
+ return new Plugin2({
2175
+ key: pluginKey,
2176
+ state: {
2177
+ init() {
2178
+ return DecorationSet.empty;
2179
+ },
2180
+ apply(tr, old) {
2181
+ const meta = tr.getMeta(META_KEY);
2182
+ if (meta) return meta;
2183
+ if (tr.docChanged) return old.map(tr.mapping, tr.doc);
2184
+ return old;
2185
+ }
2186
+ },
2187
+ props: {
2188
+ decorations(state) {
2189
+ return pluginKey.getState(state) ?? DecorationSet.empty;
2190
+ }
2191
+ },
2192
+ view(editorView) {
2193
+ scheduleUpdate(editorView);
2194
+ return {
2195
+ update(view, prevState) {
2196
+ if (!view.state.doc.eq(prevState.doc)) {
2197
+ scheduleUpdate(view);
2198
+ }
2199
+ },
2200
+ destroy() {
2201
+ if (rafId !== null) cancelAnimationFrame(rafId);
2202
+ }
2203
+ };
2204
+ }
2205
+ });
2206
+ }
2207
+ var PageLayout = Extension.create({
2208
+ name: "pageLayout",
2209
+ addOptions() {
2210
+ return { pageSize: "A4" };
2211
+ },
2212
+ addProseMirrorPlugins() {
2213
+ return [buildPageBreakPlugin(this.options.pageSize)];
2214
+ }
2215
+ });
2216
+
2217
+ // src/extensions/TabIndent.ts
2218
+ var TabIndent = Extension.create({
2219
+ name: "tabIndent",
2220
+ addKeyboardShortcuts() {
2221
+ return {
2222
+ Tab: () => this.editor.commands.insertContent(" ")
2223
+ };
2224
+ }
2225
+ });
2226
+
2227
+ // src/components/PagedEditorContent.tsx
2228
+ import { EditorContent } from "@tiptap/react";
2229
+
2230
+ // src/components/FloatingToolbar.tsx
2231
+ import { useEffect as useEffect3, useState } from "react";
2232
+ import {
2233
+ Bold,
2234
+ Italic,
2235
+ Underline,
2236
+ Heading1,
2237
+ Heading2,
2238
+ AlignLeft,
2239
+ AlignCenter,
2240
+ AlignRight,
2241
+ AlignJustify,
2242
+ List,
2243
+ ListOrdered,
2244
+ Indent,
2245
+ Outdent,
2246
+ Rows
2247
+ } from "lucide-react";
2248
+
2249
+ // src/components/FontPicker.tsx
2250
+ import { useRef, useEffect } from "react";
2251
+ import { Type } from "lucide-react";
2252
+ import { jsx, jsxs } from "react/jsx-runtime";
2253
+ var GOOGLE_FONTS_URL = "https://fonts.googleapis.com/css2?family=Dancing+Script&family=Inter&family=Roboto+Slab&family=JetBrains+Mono&display=swap";
2254
+ var FONTS = {
2255
+ cursive: { label: "Cursive", family: "'Dancing Script', cursive" },
2256
+ serif: { label: "Serif", family: "Georgia, serif" },
2257
+ sans: { label: "Sans", family: "'Inter', sans-serif" },
2258
+ slab: { label: "Slab", family: "'Roboto Slab', serif" },
2259
+ mono: { label: "Mono", family: "'JetBrains Mono', monospace" }
2260
+ };
2261
+ function FontPicker({ font, onChange, open, onToggle, onClose }) {
2262
+ const ref = useRef(null);
2263
+ useEffect(() => {
2264
+ if (!open) return;
2265
+ const handler = (e) => {
2266
+ if (!ref.current?.contains(e.target)) onClose();
2267
+ };
2268
+ document.addEventListener("mousedown", handler);
2269
+ return () => document.removeEventListener("mousedown", handler);
2270
+ }, [open, onClose]);
2271
+ return /* @__PURE__ */ jsxs("div", { className: "ink-popover-anchor", ref, children: [
2272
+ /* @__PURE__ */ jsxs(
2273
+ "button",
2274
+ {
2275
+ type: "button",
2276
+ className: `ink-toolbar-btn${open ? " ink-toolbar-btn--active" : ""}`,
2277
+ onClick: onToggle,
2278
+ "aria-label": "Font",
2279
+ title: "Font",
2280
+ style: { width: "auto", padding: "0 8px", gap: 4, fontSize: 13 },
2281
+ children: [
2282
+ /* @__PURE__ */ jsx(Type, { size: 14 }),
2283
+ FONTS[font].label
2284
+ ]
2285
+ }
2286
+ ),
2287
+ open && /* @__PURE__ */ jsx("div", { className: "ink-popover ink-popover--right ink-font-picker", role: "menu", children: Object.keys(FONTS).map((key) => /* @__PURE__ */ jsx(
2288
+ "button",
2289
+ {
2290
+ type: "button",
2291
+ role: "menuitem",
2292
+ className: `ink-font-option${font === key ? " ink-font-option--active" : ""}`,
2293
+ style: { fontFamily: FONTS[key].family },
2294
+ onClick: () => {
2295
+ onChange(key);
2296
+ onClose();
2297
+ },
2298
+ children: FONTS[key].label
2299
+ },
2300
+ key
2301
+ )) })
2302
+ ] });
2303
+ }
2304
+
2305
+ // src/components/ColorPanel.tsx
2306
+ import { useRef as useRef2, useEffect as useEffect2 } from "react";
2307
+ import { Palette } from "lucide-react";
2308
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
2309
+ var SWATCHES = {
2310
+ canvasBg: ["#e0ddd4", "#d6e4f0", "#e8f5e9", "#f3e5f5", "#fff8e1", "#2c2c2c"],
2311
+ paperColor: ["#f5f4ed", "#ffffff", "#fffde7", "#fce4ec", "#e8eaf6", "#1a1a1a"],
2312
+ textColor: ["#141413", "#111111", "#1a237e", "#4a148c", "#1b5e20", "#e0e0e0"],
2313
+ lineColor: ["#c8c4b8", "#d0d0d0", "#b0bec5", "#ce93d8", "#a5d6a7", "#555555"],
2314
+ accentColor: ["#1b365d", "#2563eb", "#00796b", "#7b1fa2", "#e65100", "#f48fb1"]
2315
+ };
2316
+ var COLOR_LABELS = {
2317
+ canvasBg: "Canvas",
2318
+ paperColor: "Paper",
2319
+ textColor: "Text",
2320
+ lineColor: "Lines",
2321
+ accentColor: "Accent"
2322
+ };
2323
+ var COLOR_KEYS = Object.keys(SWATCHES);
2324
+ function ColorPanel({ colors, onChange, open, onToggle, onClose }) {
2325
+ const ref = useRef2(null);
2326
+ useEffect2(() => {
2327
+ if (!open) return;
2328
+ const handler = (e) => {
2329
+ if (!ref.current?.contains(e.target)) onClose();
2330
+ };
2331
+ document.addEventListener("mousedown", handler);
2332
+ return () => document.removeEventListener("mousedown", handler);
2333
+ }, [open, onClose]);
2334
+ function set(key, value) {
2335
+ onChange({ ...colors, [key]: value });
2336
+ }
2337
+ return /* @__PURE__ */ jsxs2("div", { className: "ink-popover-anchor", ref, children: [
2338
+ /* @__PURE__ */ jsx2(
2339
+ "button",
2340
+ {
2341
+ type: "button",
2342
+ className: `ink-toolbar-btn${open ? " ink-toolbar-btn--active" : ""}`,
2343
+ onClick: onToggle,
2344
+ "aria-label": "Colors",
2345
+ title: "Colors",
2346
+ children: /* @__PURE__ */ jsx2(Palette, { size: 16 })
2347
+ }
2348
+ ),
2349
+ open && /* @__PURE__ */ jsx2("div", { className: "ink-popover ink-popover--right ink-color-panel", role: "dialog", "aria-label": "Color customization", children: COLOR_KEYS.map((key) => /* @__PURE__ */ jsxs2("div", { className: "ink-color-row", children: [
2350
+ /* @__PURE__ */ jsx2("span", { className: "ink-color-label", children: COLOR_LABELS[key] }),
2351
+ /* @__PURE__ */ jsxs2("div", { className: "ink-swatches", children: [
2352
+ SWATCHES[key].map((swatch) => /* @__PURE__ */ jsx2(
2353
+ "button",
2354
+ {
2355
+ type: "button",
2356
+ className: `ink-swatch${colors[key] === swatch ? " ink-swatch--active" : ""}`,
2357
+ style: { background: swatch },
2358
+ "aria-label": swatch,
2359
+ title: swatch,
2360
+ onClick: () => set(key, swatch)
2361
+ },
2362
+ swatch
2363
+ )),
2364
+ /* @__PURE__ */ jsx2("span", { className: "ink-color-custom", title: "Custom color", children: /* @__PURE__ */ jsx2(
2365
+ "input",
2366
+ {
2367
+ type: "color",
2368
+ value: colors[key],
2369
+ onChange: (e) => set(key, e.target.value),
2370
+ "aria-label": `Custom ${COLOR_LABELS[key]} color`
2371
+ }
2372
+ ) })
2373
+ ] })
2374
+ ] }, key)) })
2375
+ ] });
2376
+ }
2377
+
2378
+ // src/components/FloatingToolbar.tsx
2379
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
2380
+ function Sep() {
2381
+ return /* @__PURE__ */ jsx3("span", { className: "ink-toolbar-sep", "aria-hidden": "true" });
2382
+ }
2383
+ function FloatingToolbar({
2384
+ editor,
2385
+ buttons,
2386
+ ruled,
2387
+ onToggleRuled,
2388
+ font,
2389
+ onFontChange,
2390
+ colors,
2391
+ onColorsChange
2392
+ }) {
2393
+ const [openPanel, setOpenPanel] = useState(null);
2394
+ useEffect3(() => {
2395
+ if (document.querySelector(`link[href="${GOOGLE_FONTS_URL}"]`)) return;
2396
+ const link = document.createElement("link");
2397
+ link.rel = "stylesheet";
2398
+ link.href = GOOGLE_FONTS_URL;
2399
+ document.head.appendChild(link);
2400
+ }, []);
2401
+ function togglePanel(panel) {
2402
+ setOpenPanel((prev) => prev === panel ? null : panel);
2403
+ }
2404
+ const iconSize = 16;
2405
+ const allGroups = [
2406
+ {
2407
+ key: "bold",
2408
+ configs: [{
2409
+ label: "Bold",
2410
+ icon: /* @__PURE__ */ jsx3(Bold, { size: iconSize }),
2411
+ isActive: () => editor.isActive("bold"),
2412
+ action: () => editor.chain().focus().toggleBold().run()
2413
+ }]
2414
+ },
2415
+ {
2416
+ key: "italic",
2417
+ configs: [{
2418
+ label: "Italic",
2419
+ icon: /* @__PURE__ */ jsx3(Italic, { size: iconSize }),
2420
+ isActive: () => editor.isActive("italic"),
2421
+ action: () => editor.chain().focus().toggleItalic().run()
2422
+ }]
2423
+ },
2424
+ {
2425
+ key: "underline",
2426
+ configs: [{
2427
+ label: "Underline",
2428
+ icon: /* @__PURE__ */ jsx3(Underline, { size: iconSize }),
2429
+ isActive: () => editor.isActive("underline"),
2430
+ action: () => editor.chain().focus().toggleUnderline().run()
2431
+ }]
2432
+ },
2433
+ {
2434
+ key: "h1",
2435
+ configs: [{
2436
+ label: "Heading 1",
2437
+ icon: /* @__PURE__ */ jsx3(Heading1, { size: iconSize }),
2438
+ isActive: () => editor.isActive("heading", { level: 1 }),
2439
+ action: () => editor.chain().focus().toggleHeading({ level: 1 }).run()
2440
+ }]
2441
+ },
2442
+ {
2443
+ key: "h2",
2444
+ configs: [{
2445
+ label: "Heading 2",
2446
+ icon: /* @__PURE__ */ jsx3(Heading2, { size: iconSize }),
2447
+ isActive: () => editor.isActive("heading", { level: 2 }),
2448
+ action: () => editor.chain().focus().toggleHeading({ level: 2 }).run()
2449
+ }]
2450
+ },
2451
+ {
2452
+ key: "align",
2453
+ configs: [
2454
+ { label: "Align left", icon: /* @__PURE__ */ jsx3(AlignLeft, { size: iconSize }), isActive: () => editor.isActive({ textAlign: "left" }), action: () => editor.chain().focus().setTextAlign("left").run() },
2455
+ { label: "Align center", icon: /* @__PURE__ */ jsx3(AlignCenter, { size: iconSize }), isActive: () => editor.isActive({ textAlign: "center" }), action: () => editor.chain().focus().setTextAlign("center").run() },
2456
+ { label: "Align right", icon: /* @__PURE__ */ jsx3(AlignRight, { size: iconSize }), isActive: () => editor.isActive({ textAlign: "right" }), action: () => editor.chain().focus().setTextAlign("right").run() },
2457
+ { label: "Justify", icon: /* @__PURE__ */ jsx3(AlignJustify, { size: iconSize }), isActive: () => editor.isActive({ textAlign: "justify" }), action: () => editor.chain().focus().setTextAlign("justify").run() }
2458
+ ]
2459
+ },
2460
+ {
2461
+ key: "list",
2462
+ configs: [
2463
+ { label: "Bullet list", icon: /* @__PURE__ */ jsx3(List, { size: iconSize }), isActive: () => editor.isActive("bulletList"), action: () => editor.chain().focus().toggleBulletList().run() },
2464
+ { label: "Ordered list", icon: /* @__PURE__ */ jsx3(ListOrdered, { size: iconSize }), isActive: () => editor.isActive("orderedList"), action: () => editor.chain().focus().toggleOrderedList().run() }
2465
+ ]
2466
+ },
2467
+ {
2468
+ key: "indent",
2469
+ configs: [
2470
+ { label: "Indent", icon: /* @__PURE__ */ jsx3(Indent, { size: iconSize }), isActive: () => false, action: () => editor.chain().focus().sinkListItem("listItem").run() },
2471
+ { label: "Outdent", icon: /* @__PURE__ */ jsx3(Outdent, { size: iconSize }), isActive: () => false, action: () => editor.chain().focus().liftListItem("listItem").run() }
2472
+ ]
2473
+ },
2474
+ {
2475
+ key: "lines",
2476
+ configs: [{
2477
+ label: "Toggle ruled lines",
2478
+ icon: /* @__PURE__ */ jsx3(Rows, { size: iconSize }),
2479
+ isActive: () => ruled,
2480
+ action: onToggleRuled
2481
+ }]
2482
+ }
2483
+ ];
2484
+ const activeGroups = allGroups.filter((g) => buttons.includes(g.key));
2485
+ return /* @__PURE__ */ jsx3("div", { className: "ink-floating-toolbar-wrap", children: /* @__PURE__ */ jsxs3("div", { className: "ink-floating-toolbar", role: "toolbar", "aria-label": "Text formatting", children: [
2486
+ activeGroups.map((group, gi) => /* @__PURE__ */ jsxs3("span", { className: "ink-toolbar-group", style: { display: "contents" }, children: [
2487
+ group.configs.map((cfg) => /* @__PURE__ */ jsx3(
2488
+ "button",
2489
+ {
2490
+ type: "button",
2491
+ className: `ink-toolbar-btn${cfg.isActive() ? " ink-toolbar-btn--active" : ""}`,
2492
+ onClick: cfg.action,
2493
+ "aria-label": cfg.label,
2494
+ title: cfg.label,
2495
+ children: cfg.icon
2496
+ },
2497
+ cfg.label
2498
+ )),
2499
+ gi < activeGroups.length - 1 && /* @__PURE__ */ jsx3(Sep, {})
2500
+ ] }, group.key)),
2501
+ activeGroups.length > 0 && /* @__PURE__ */ jsx3(Sep, {}),
2502
+ /* @__PURE__ */ jsx3(
2503
+ FontPicker,
2504
+ {
2505
+ font,
2506
+ onChange: onFontChange,
2507
+ open: openPanel === "font",
2508
+ onToggle: () => togglePanel("font"),
2509
+ onClose: () => setOpenPanel(null)
2510
+ }
2511
+ ),
2512
+ /* @__PURE__ */ jsx3(
2513
+ ColorPanel,
2514
+ {
2515
+ colors,
2516
+ onChange: onColorsChange,
2517
+ open: openPanel === "color",
2518
+ onToggle: () => togglePanel("color"),
2519
+ onClose: () => setOpenPanel(null)
2520
+ }
2521
+ )
2522
+ ] }) });
2523
+ }
2524
+
2525
+ // src/components/PagedEditorContent.tsx
2526
+ import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
2527
+ function PagedEditorContent({
2528
+ editor,
2529
+ pageSize,
2530
+ theme,
2531
+ toolbar,
2532
+ ruled,
2533
+ onToggleRuled,
2534
+ font,
2535
+ onFontChange,
2536
+ colors,
2537
+ onColorsChange
2538
+ }) {
2539
+ const widthPx = getPageWidthPx(pageSize);
2540
+ const bodyWidthPx = getBodyWidthPx(pageSize);
2541
+ const dims = PAGE_DIMENSIONS[pageSize];
2542
+ const pageHeightPx = Math.round(dims.heightMm * 3.7795);
2543
+ const hasToolbar = toolbar.length > 0;
2544
+ const bodyHeightPx = getBodyHeightPx(pageSize);
2545
+ return /* @__PURE__ */ jsxs4(
2546
+ "div",
2547
+ {
2548
+ className: "ink-page-wrap",
2549
+ "data-theme": theme,
2550
+ style: {
2551
+ "--ink-bg": colors.canvasBg,
2552
+ "--ink-page": colors.paperColor,
2553
+ "--ink-text": colors.textColor,
2554
+ "--ink-border-line": colors.lineColor,
2555
+ "--ink-accent": colors.accentColor,
2556
+ "--ink-font-body": FONTS[font].family
2557
+ },
2558
+ children: [
2559
+ editor && hasToolbar && /* @__PURE__ */ jsx4(
2560
+ FloatingToolbar,
2561
+ {
2562
+ editor,
2563
+ buttons: toolbar,
2564
+ ruled,
2565
+ onToggleRuled,
2566
+ font,
2567
+ onFontChange,
2568
+ colors,
2569
+ onColorsChange
2570
+ }
2571
+ ),
2572
+ /* @__PURE__ */ jsx4(
2573
+ "div",
2574
+ {
2575
+ className: `ink-page-card${ruled ? " ink-ruled" : ""}`,
2576
+ style: {
2577
+ width: widthPx,
2578
+ minHeight: pageHeightPx,
2579
+ padding: `${dims.paddingTopMm}mm ${dims.paddingRightMm}mm ${dims.paddingBottomMm}mm ${dims.paddingLeftMm}mm`,
2580
+ ["--ink-padding-top"]: `${dims.paddingTopMm}mm`,
2581
+ ["--ink-padding-right"]: `${dims.paddingRightMm}mm`,
2582
+ ["--ink-padding-left"]: `${dims.paddingLeftMm}mm`,
2583
+ ["--ink-body-width"]: `${bodyWidthPx}px`,
2584
+ ["--ink-body-height"]: `${bodyHeightPx}px`
2585
+ },
2586
+ children: /* @__PURE__ */ jsx4(EditorContent, { editor })
2587
+ }
2588
+ )
2589
+ ]
2590
+ }
2591
+ );
2592
+ }
2593
+
2594
+ // src/InkEditor.tsx
2595
+ import { jsx as jsx5 } from "react/jsx-runtime";
2596
+ var DEFAULT_TOOLBAR = ["bold", "italic", "underline", "h1", "h2", "align", "list", "indent", "lines"];
2597
+ function InkEditor({
2598
+ pageSize = "A4",
2599
+ onChange,
2600
+ theme = "parchment",
2601
+ toolbar = DEFAULT_TOOLBAR
2602
+ }) {
2603
+ const [ruled, setRuled] = useState2(false);
2604
+ const [font, setFont] = useState2("cursive");
2605
+ const [colors, setColors] = useState2(
2606
+ theme === "minimal" ? MINIMAL_DEFAULTS : PARCHMENT_DEFAULTS
2607
+ );
2608
+ const editor = useEditor({
2609
+ extensions: [
2610
+ StarterKit,
2611
+ PageLayout.configure({ pageSize }),
2612
+ TextAlign.configure({ types: ["heading", "paragraph"] }),
2613
+ Underline2,
2614
+ TabIndent
2615
+ ],
2616
+ onUpdate({ editor: editor2 }) {
2617
+ onChange?.(editor2.getJSON());
2618
+ }
2619
+ });
2620
+ useEffect4(() => {
2621
+ return () => {
2622
+ editor?.destroy();
2623
+ };
2624
+ }, [editor]);
2625
+ return /* @__PURE__ */ jsx5(
2626
+ PagedEditorContent,
2627
+ {
2628
+ editor,
2629
+ pageSize,
2630
+ theme,
2631
+ toolbar,
2632
+ ruled,
2633
+ onToggleRuled: () => setRuled((r) => !r),
2634
+ font,
2635
+ onFontChange: setFont,
2636
+ colors,
2637
+ onColorsChange: setColors
2638
+ }
2639
+ );
2640
+ }
2641
+ export {
2642
+ InkEditor,
2643
+ MINIMAL_DEFAULTS,
2644
+ PARCHMENT_DEFAULTS
2645
+ };
2646
+ //# sourceMappingURL=index.mjs.map