@novaprose/core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/advlist-FRIJ6LO7.js +107 -0
  2. package/dist/advlist-FRIJ6LO7.js.map +1 -0
  3. package/dist/autolink-ZVHNOOS7.js +89 -0
  4. package/dist/autolink-ZVHNOOS7.js.map +1 -0
  5. package/dist/autoresize-WT4ONZKK.js +26 -0
  6. package/dist/autoresize-WT4ONZKK.js.map +1 -0
  7. package/dist/autosave-2KI5WGV5.js +99 -0
  8. package/dist/autosave-2KI5WGV5.js.map +1 -0
  9. package/dist/charmap-3LM5LZCC.js +197 -0
  10. package/dist/charmap-3LM5LZCC.js.map +1 -0
  11. package/dist/chunk-6RJENZXT.js +104 -0
  12. package/dist/chunk-6RJENZXT.js.map +1 -0
  13. package/dist/{chunk-TKR3C5IJ.js → chunk-AGBQEZ2U.js} +300 -681
  14. package/dist/chunk-AGBQEZ2U.js.map +1 -0
  15. package/dist/{chunk-ZF2JR3JH.js → chunk-F6TSOU5U.js} +1 -1
  16. package/dist/chunk-F6TSOU5U.js.map +1 -0
  17. package/dist/chunk-GHEFKKRC.js +268 -0
  18. package/dist/chunk-GHEFKKRC.js.map +1 -0
  19. package/dist/chunk-HZRIBOPW.js +52 -0
  20. package/dist/chunk-HZRIBOPW.js.map +1 -0
  21. package/dist/chunk-YZPJQB3I.js +490 -0
  22. package/dist/chunk-YZPJQB3I.js.map +1 -0
  23. package/dist/directionality-VSDWPWHX.js +70 -0
  24. package/dist/directionality-VSDWPWHX.js.map +1 -0
  25. package/dist/emoticons-YVGVA76P.js +216 -0
  26. package/dist/emoticons-YVGVA76P.js.map +1 -0
  27. package/dist/index.cjs +3762 -1175
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +177 -10
  30. package/dist/index.d.ts +177 -10
  31. package/dist/index.js +1316 -95
  32. package/dist/index.js.map +1 -1
  33. package/dist/{insertdatetime-C4MAC5L7.js → insertdatetime-QYWZUYO4.js} +2 -2
  34. package/dist/nonbreaking-SIACL5V6.js +46 -0
  35. package/dist/nonbreaking-SIACL5V6.js.map +1 -0
  36. package/dist/{quickbars-XK4QCQ6F.js → quickbars-WW3TGVCS.js} +7 -5
  37. package/dist/quickbars-WW3TGVCS.js.map +1 -0
  38. package/dist/visualblocks-WB6NAEGB.js +43 -0
  39. package/dist/visualblocks-WB6NAEGB.js.map +1 -0
  40. package/package.json +5 -2
  41. package/src/style.css +180 -0
  42. package/dist/chunk-TKR3C5IJ.js.map +0 -1
  43. package/dist/chunk-ZF2JR3JH.js.map +0 -1
  44. package/dist/quickbars-XK4QCQ6F.js.map +0 -1
  45. /package/dist/{insertdatetime-C4MAC5L7.js.map → insertdatetime-QYWZUYO4.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,47 +1,66 @@
1
1
  import {
2
2
  applyLink,
3
- commands,
4
3
  createTable,
5
4
  createTableGridPanel,
6
- cssValue,
7
- formatShortcut,
8
- getActiveAlign,
9
- getLinkAt,
5
+ embeddedImageUploadPlugin,
6
+ getCellProps,
10
7
  getSelectedImage,
11
- h,
8
+ getTableProps,
12
9
  hasHeaderColumn,
13
10
  hasHeaderRow,
14
- icon,
15
11
  icons,
16
12
  imageDropPastePlugin,
17
- imageSize,
18
- insertImage,
19
13
  insertTable,
20
- isCommandActive,
21
14
  isInTable,
22
- isMarkActive,
23
- isNodeActive,
24
- isSafeImageUrl,
25
- isSafeLinkUrl,
26
- markRange,
27
15
  normalizeUrl,
28
16
  openDialog,
29
17
  openImageAltDialog,
30
18
  openImageDialog,
31
19
  openLinkDialog,
32
20
  removeLink,
33
- schema,
21
+ selectField,
34
22
  setCellBackground,
23
+ setCellProps,
35
24
  setImageAttrs,
36
25
  setImageWidthFraction,
37
- setLink,
26
+ setTableProps,
27
+ sortTable,
38
28
  tableCommands,
39
29
  tablePlugins,
40
30
  tableRect,
41
31
  textField,
42
- uniqueId,
43
32
  uploadImages
44
- } from "./chunk-TKR3C5IJ.js";
33
+ } from "./chunk-AGBQEZ2U.js";
34
+ import {
35
+ createSchema,
36
+ cssValue,
37
+ imageSize,
38
+ schema
39
+ } from "./chunk-YZPJQB3I.js";
40
+ import {
41
+ commands,
42
+ getActiveAlign,
43
+ getLinkAt,
44
+ insertImage,
45
+ isCommandActive,
46
+ isMarkActive,
47
+ isNodeActive,
48
+ isSafeImageUrl,
49
+ isSafeLinkUrl,
50
+ markRange,
51
+ marksOf,
52
+ nodesOf,
53
+ setLink
54
+ } from "./chunk-GHEFKKRC.js";
55
+ import {
56
+ pickLabels
57
+ } from "./chunk-6RJENZXT.js";
58
+ import {
59
+ formatShortcut,
60
+ h,
61
+ icon,
62
+ uniqueId
63
+ } from "./chunk-HZRIBOPW.js";
45
64
  import {
46
65
  definePlugin,
47
66
  isPluginRegistered,
@@ -49,11 +68,342 @@ import {
49
68
  orderPlugins,
50
69
  registerPlugin,
51
70
  resolveEntries
52
- } from "./chunk-ZF2JR3JH.js";
71
+ } from "./chunk-F6TSOU5U.js";
72
+
73
+ // src/plugins/anchor.ts
74
+ import { NodeSelection } from "prosemirror-state";
75
+ var ICON = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="5" r="2"/><path d="M12 7v14M5 12H3a9 9 0 0 0 18 0h-2"/></svg>';
76
+ var LABELS = {
77
+ en: {
78
+ title: "Anchor",
79
+ id: "ID",
80
+ hint: "Letters, digits, \u201C-\u201D, \u201C_\u201D, \u201C.\u201D; must start with a letter. Link to it with #ID.",
81
+ invalid: "Use letters, digits, \u201C-\u201D, \u201C_\u201D or \u201C.\u201D, starting with a letter",
82
+ save: "Save"
83
+ },
84
+ ru: {
85
+ title: "\u042F\u043A\u043E\u0440\u044C",
86
+ id: "\u0418\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440",
87
+ hint: "\u041B\u0430\u0442\u0438\u043D\u0441\u043A\u0438\u0435 \u0431\u0443\u043A\u0432\u044B, \u0446\u0438\u0444\u0440\u044B, \xAB-\xBB, \xAB_\xBB, \xAB.\xBB; \u043D\u0430\u0447\u0438\u043D\u0430\u0435\u0442\u0441\u044F \u0441 \u0431\u0443\u043A\u0432\u044B. \u0421\u0441\u044B\u043B\u043A\u0430 \u043D\u0430 \u044F\u043A\u043E\u0440\u044C \u2014 #\u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440.",
88
+ invalid: "\u0422\u043E\u043B\u044C\u043A\u043E \u043B\u0430\u0442\u0438\u043D\u0441\u043A\u0438\u0435 \u0431\u0443\u043A\u0432\u044B, \u0446\u0438\u0444\u0440\u044B, \xAB-\xBB, \xAB_\xBB \u0438\u043B\u0438 \xAB.\xBB, \u043F\u0435\u0440\u0432\u0430\u044F \u2014 \u0431\u0443\u043A\u0432\u0430",
89
+ save: "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C"
90
+ }
91
+ };
92
+ var ID_RE = /^[A-Za-z][\w.-]{0,63}$/;
93
+ var anchor_default = definePlugin({
94
+ name: "anchor",
95
+ toolbar: "anchor",
96
+ nodes: {
97
+ anchor: {
98
+ group: "inline",
99
+ inline: true,
100
+ atom: true,
101
+ selectable: true,
102
+ attrs: { id: {} },
103
+ parseDOM: [
104
+ {
105
+ tag: "a[id]:not([href])",
106
+ getAttrs: (dom) => {
107
+ const id = dom.getAttribute("id") ?? "";
108
+ return ID_RE.test(id) ? { id } : false;
109
+ }
110
+ },
111
+ {
112
+ tag: "a[name]:not([href])",
113
+ getAttrs: (dom) => {
114
+ const id = dom.getAttribute("name") ?? "";
115
+ return ID_RE.test(id) ? { id } : false;
116
+ }
117
+ }
118
+ ],
119
+ // Документ мог прийти из JSON — идентификатор проверяем и на выходе.
120
+ toDOM: (node) => ["a", { id: ID_RE.test(node.attrs.id) ? node.attrs.id : null }]
121
+ }
122
+ },
123
+ setup(editor) {
124
+ const labels = pickLabels(editor, LABELS);
125
+ const selectedAnchor = () => {
126
+ const { selection } = editor.view.state;
127
+ return selection instanceof NodeSelection && selection.node.type.name === "anchor" ? selection : null;
128
+ };
129
+ const open = () => {
130
+ const current = selectedAnchor();
131
+ const field = textField({
132
+ label: labels.id,
133
+ hint: labels.hint,
134
+ value: current?.node.attrs.id ?? ""
135
+ });
136
+ editor.ui.openDialog({
137
+ title: labels.title,
138
+ body: h("div", { className: "nova-form" }, field.el),
139
+ submitLabel: labels.save,
140
+ onSubmit: () => {
141
+ const id = field.input.value.trim();
142
+ if (!ID_RE.test(id)) return labels.invalid;
143
+ const { state, dispatch } = editor.view;
144
+ const type = editor.schema.nodes.anchor;
145
+ const sel = selectedAnchor();
146
+ if (sel) dispatch(state.tr.setNodeMarkup(sel.from, void 0, { id }));
147
+ else dispatch(state.tr.replaceSelectionWith(type.create({ id }), false).scrollIntoView());
148
+ return true;
149
+ }
150
+ });
151
+ };
152
+ editor.ui.registry.addToggleButton("anchor", {
153
+ icon: ICON,
154
+ tooltip: labels.title,
155
+ isActive: () => selectedAnchor() !== null,
156
+ isEnabled: (e) => e.isEditable(),
157
+ onAction: open
158
+ });
159
+ editor.ui.registry.addMenuItem("anchor", { text: labels.title, icon: ICON, onAction: open });
160
+ }
161
+ });
162
+
163
+ // src/plugins/media.ts
164
+ import { NodeSelection as NodeSelection2, Plugin } from "prosemirror-state";
165
+ var YOUTUBE = /^https?:\/\/(?:www\.|m\.)?(?:youtube(?:-nocookie)?\.com\/(?:watch\?(?:[^#]*&)?v=|embed\/|shorts\/|live\/)|youtu\.be\/)([\w-]{11})(?:[?&#]|$)/i;
166
+ var VIMEO = /^https?:\/\/(?:www\.|player\.)?vimeo\.com\/(?:video\/)?(\d{1,12})(?:[/?#]|$)/i;
167
+ var VIDEO_FILE = /^https:\/\/[^\s"'<>]+\.(?:mp4|webm|ogv|ogg)(?:\?[^\s"'<>#]*)?$/i;
168
+ function parseMediaUrl(url) {
169
+ const value = url.trim();
170
+ const youtube = value.match(YOUTUBE);
171
+ if (youtube)
172
+ return { kind: "youtube", src: `https://www.youtube-nocookie.com/embed/${youtube[1]}` };
173
+ const vimeo = value.match(VIMEO);
174
+ if (vimeo) return { kind: "vimeo", src: `https://player.vimeo.com/video/${vimeo[1]}` };
175
+ if (VIDEO_FILE.test(value)) return { kind: "video", src: value };
176
+ return null;
177
+ }
178
+ var ICON2 = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="5" width="20" height="14" rx="2"/><path d="m10 9 5 3-5 3z"/></svg>';
179
+ var LABELS2 = {
180
+ en: {
181
+ title: "Video",
182
+ url: "Video URL",
183
+ hint: "YouTube, Vimeo or a link to an .mp4 / .webm file",
184
+ name: "Title (for screen readers)",
185
+ invalid: "This video address is not supported",
186
+ save: "Insert"
187
+ },
188
+ ru: {
189
+ title: "\u0412\u0438\u0434\u0435\u043E",
190
+ url: "\u0410\u0434\u0440\u0435\u0441 \u0432\u0438\u0434\u0435\u043E",
191
+ hint: "YouTube, Vimeo \u0438\u043B\u0438 \u0441\u0441\u044B\u043B\u043A\u0430 \u043D\u0430 \u0444\u0430\u0439\u043B .mp4 / .webm",
192
+ name: "\u041D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 (\u0434\u043B\u044F \u044D\u043A\u0440\u0430\u043D\u043D\u043E\u0433\u043E \u0434\u0438\u043A\u0442\u043E\u0440\u0430)",
193
+ invalid: "\u042D\u0442\u043E\u0442 \u0430\u0434\u0440\u0435\u0441 \u0432\u0438\u0434\u0435\u043E \u043D\u0435 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F",
194
+ save: "\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u044C"
195
+ }
196
+ };
197
+ function mediaAttrs(dom, src) {
198
+ const source = src ? parseMediaUrl(src) : null;
199
+ if (!source) return false;
200
+ return {
201
+ ...source,
202
+ width: imageSize(dom.getAttribute("width")) ?? 560,
203
+ height: imageSize(dom.getAttribute("height")) ?? 315,
204
+ title: dom.getAttribute("title") ?? ""
205
+ };
206
+ }
207
+ function renderMedia(node) {
208
+ const source = parseMediaUrl(node.attrs.src);
209
+ if (!source) return null;
210
+ const width = String(imageSize(node.attrs.width) ?? 560);
211
+ const height = String(imageSize(node.attrs.height) ?? 315);
212
+ if (source.kind === "video") {
213
+ return h("video", { src: source.src, controls: true, width, height, preload: "metadata" });
214
+ }
215
+ return h("iframe", {
216
+ src: source.src,
217
+ width,
218
+ height,
219
+ title: node.attrs.title || "Video",
220
+ allow: "accelerometer; encrypted-media; gyroscope; picture-in-picture; fullscreen",
221
+ allowfullscreen: true,
222
+ loading: "lazy",
223
+ referrerpolicy: "strict-origin-when-cross-origin"
224
+ });
225
+ }
226
+ var media_default = definePlugin({
227
+ name: "media",
228
+ toolbar: "media",
229
+ nodes: {
230
+ media: {
231
+ group: "block",
232
+ atom: true,
233
+ selectable: true,
234
+ draggable: true,
235
+ attrs: {
236
+ kind: { default: "youtube" },
237
+ src: {},
238
+ width: { default: 560 },
239
+ height: { default: 315 },
240
+ title: { default: "" }
241
+ },
242
+ parseDOM: [
243
+ {
244
+ tag: "iframe[src]",
245
+ getAttrs: (dom) => mediaAttrs(dom, dom.getAttribute("src"))
246
+ },
247
+ {
248
+ tag: "video",
249
+ getAttrs: (dom) => {
250
+ const el = dom;
251
+ const src = el.getAttribute("src") ?? el.querySelector("source[src]")?.getAttribute("src") ?? null;
252
+ return mediaAttrs(el, src);
253
+ }
254
+ }
255
+ ],
256
+ toDOM: (node) => {
257
+ const source = parseMediaUrl(node.attrs.src);
258
+ const width = String(imageSize(node.attrs.width) ?? 560);
259
+ const height = String(imageSize(node.attrs.height) ?? 315);
260
+ if (!source) return ["p"];
261
+ if (source.kind === "video")
262
+ return ["video", { src: source.src, controls: "", width, height }];
263
+ return [
264
+ "iframe",
265
+ {
266
+ src: source.src,
267
+ width,
268
+ height,
269
+ title: node.attrs.title || null,
270
+ allow: "accelerometer; encrypted-media; gyroscope; picture-in-picture; fullscreen",
271
+ allowfullscreen: "",
272
+ loading: "lazy",
273
+ referrerpolicy: "strict-origin-when-cross-origin"
274
+ }
275
+ ];
276
+ }
277
+ }
278
+ },
279
+ prosemirrorPlugins: () => [
280
+ new Plugin({
281
+ props: {
282
+ nodeViews: {
283
+ // В редакторе плеер закрыт прозрачным слоем: клик выделяет блок, а не запускает видео.
284
+ media: (node) => {
285
+ const player = renderMedia(node);
286
+ const dom = h(
287
+ "div",
288
+ { className: "nova-media", contenteditable: "false" },
289
+ player,
290
+ h("div", { className: "nova-media-overlay", "aria-hidden": "true" })
291
+ );
292
+ return { dom, ignoreMutation: () => true, stopEvent: () => false };
293
+ }
294
+ }
295
+ }
296
+ })
297
+ ],
298
+ setup(editor) {
299
+ const labels = pickLabels(editor, LABELS2);
300
+ const selected = () => {
301
+ const { selection } = editor.view.state;
302
+ return selection instanceof NodeSelection2 && selection.node.type.name === "media" ? selection : null;
303
+ };
304
+ const open = () => {
305
+ const current = selected();
306
+ const url = textField({
307
+ label: labels.url,
308
+ type: "url",
309
+ placeholder: "https://",
310
+ hint: labels.hint,
311
+ value: current?.node.attrs.src ?? ""
312
+ });
313
+ const title = textField({
314
+ label: labels.name,
315
+ value: current?.node.attrs.title ?? ""
316
+ });
317
+ editor.ui.openDialog({
318
+ title: labels.title,
319
+ body: h("div", { className: "nova-form" }, url.el, title.el),
320
+ submitLabel: labels.save,
321
+ onSubmit: () => {
322
+ const source = parseMediaUrl(url.input.value);
323
+ if (!source) return labels.invalid;
324
+ const { state, dispatch } = editor.view;
325
+ const attrs = { ...source, title: title.input.value.trim() };
326
+ const sel = selected();
327
+ if (sel)
328
+ dispatch(state.tr.setNodeMarkup(sel.from, void 0, { ...sel.node.attrs, ...attrs }));
329
+ else
330
+ dispatch(
331
+ state.tr.replaceSelectionWith(editor.schema.nodes.media.create(attrs)).scrollIntoView()
332
+ );
333
+ return true;
334
+ }
335
+ });
336
+ };
337
+ editor.ui.registry.addToggleButton("media", {
338
+ icon: ICON2,
339
+ tooltip: labels.title,
340
+ isActive: () => selected() !== null,
341
+ isEnabled: (e) => e.isEditable(),
342
+ onAction: open
343
+ });
344
+ editor.ui.registry.addMenuItem("media", { text: labels.title, icon: ICON2, onAction: open });
345
+ }
346
+ });
347
+
348
+ // src/plugins/pagebreak.ts
349
+ var ICON3 = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 3v5h12V3M6 21v-5h12v5"/><path d="M3 12h2M9 12h2M15 12h2M21 12h-0"/></svg>';
350
+ var LABELS3 = { en: { title: "Page break" }, ru: { title: "\u0420\u0430\u0437\u0440\u044B\u0432 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B" } };
351
+ var pagebreak_default = definePlugin({
352
+ name: "pagebreak",
353
+ toolbar: "pagebreak",
354
+ nodes: {
355
+ pagebreak: {
356
+ group: "block",
357
+ atom: true,
358
+ selectable: true,
359
+ parseDOM: [
360
+ { tag: "div.nova-pagebreak" },
361
+ // Разрыв из других редакторов и Word: пустой блок с page-break-after / break-after.
362
+ {
363
+ tag: "div",
364
+ getAttrs: (dom) => {
365
+ const el = dom;
366
+ const breaks = el.style.breakAfter === "page" || el.style.pageBreakAfter === "always";
367
+ return breaks && !el.textContent?.trim() ? null : false;
368
+ }
369
+ }
370
+ ],
371
+ toDOM: () => ["div", { class: "nova-pagebreak", style: "break-after: page;" }]
372
+ }
373
+ },
374
+ setup(editor) {
375
+ const { title } = pickLabels(editor, LABELS3);
376
+ const insert = () => {
377
+ const { state, dispatch } = editor.view;
378
+ const type = editor.schema.nodes.pagebreak;
379
+ dispatch(state.tr.replaceSelectionWith(type.create()).scrollIntoView());
380
+ editor.focus();
381
+ };
382
+ editor.ui.registry.addButton("pagebreak", {
383
+ icon: ICON3,
384
+ tooltip: title,
385
+ isEnabled: (e) => e.isEditable(),
386
+ onAction: insert
387
+ });
388
+ editor.ui.registry.addMenuItem("pagebreak", { text: title, icon: ICON3, onAction: insert });
389
+ }
390
+ });
53
391
 
54
392
  // src/plugins/index.ts
55
- registerPlugin("insertdatetime", () => import("./insertdatetime-C4MAC5L7.js"));
56
- registerPlugin("quickbars", () => import("./quickbars-XK4QCQ6F.js"));
393
+ registerPlugin("insertdatetime", () => import("./insertdatetime-QYWZUYO4.js"));
394
+ registerPlugin("quickbars", () => import("./quickbars-WW3TGVCS.js"));
395
+ registerPlugin("charmap", () => import("./charmap-3LM5LZCC.js"));
396
+ registerPlugin("emoticons", () => import("./emoticons-YVGVA76P.js"));
397
+ registerPlugin("nonbreaking", () => import("./nonbreaking-SIACL5V6.js"));
398
+ registerPlugin("autolink", () => import("./autolink-ZVHNOOS7.js"));
399
+ registerPlugin("autosave", () => import("./autosave-2KI5WGV5.js"));
400
+ registerPlugin("autoresize", () => import("./autoresize-WT4ONZKK.js"));
401
+ registerPlugin("visualblocks", () => import("./visualblocks-WB6NAEGB.js"));
402
+ registerPlugin("anchor", anchor_default);
403
+ registerPlugin("pagebreak", pagebreak_default);
404
+ registerPlugin("media", media_default);
405
+ registerPlugin("directionality", () => import("./directionality-VSDWPWHX.js"));
406
+ registerPlugin("advlist", () => import("./advlist-FRIJ6LO7.js"));
57
407
 
58
408
  // src/editor.ts
59
409
  import { dropCursor } from "prosemirror-dropcursor";
@@ -67,6 +417,7 @@ import { EditorView } from "prosemirror-view";
67
417
  // src/i18n/en.ts
68
418
  var en = {
69
419
  "toolbar.label": "Formatting",
420
+ "toolbar.options": "options",
70
421
  "editor.label": "Rich text editor",
71
422
  "editor.required": "Please fill in this field.",
72
423
  undo: "Undo",
@@ -207,6 +558,28 @@ var en = {
207
558
  "table.colHeader": "Header column",
208
559
  "table.cellBackground": "Cell background",
209
560
  "table.delete": "Delete table",
561
+ "table.sort": "Sort",
562
+ "table.sortAsc": "Sort A \u2192 Z, 1 \u2192 9",
563
+ "table.sortDesc": "Sort Z \u2192 A, 9 \u2192 1",
564
+ "table.props": "Table properties",
565
+ "table.width": "Width",
566
+ "table.widthHint": "For example 100% or 600px. Leave empty to fit the content.",
567
+ "table.invalidWidth": "Enter a width such as 100% or 600px",
568
+ "table.align": "Alignment on the page",
569
+ "table.alignDefault": "Default",
570
+ "table.alignCenter": "Center",
571
+ "table.alignRight": "Right",
572
+ "table.cellProps": "Cell properties",
573
+ "table.valign": "Vertical alignment",
574
+ "table.valignTop": "Top",
575
+ "table.valignMiddle": "Middle",
576
+ "table.valignBottom": "Bottom",
577
+ "table.cellType": "Cell type",
578
+ "table.cellData": "Data cell",
579
+ "table.cellHeader": "Header cell",
580
+ "table.colWidth": "Column width, px",
581
+ "table.colWidthHint": "Leave empty to fit the content.",
582
+ "table.invalidColWidth": "Enter a number from 24 to 4000",
210
583
  "slash.label": "Commands",
211
584
  "slash.empty": "No matching commands"
212
585
  };
@@ -214,6 +587,7 @@ var en = {
214
587
  // src/i18n/ru.ts
215
588
  var ru = {
216
589
  "toolbar.label": "\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",
590
+ "toolbar.options": "\u0432\u0430\u0440\u0438\u0430\u043D\u0442\u044B",
217
591
  "editor.label": "\u0422\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440",
218
592
  "editor.required": "\u0417\u0430\u043F\u043E\u043B\u043D\u0438\u0442\u0435 \u044D\u0442\u043E \u043F\u043E\u043B\u0435.",
219
593
  undo: "\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C",
@@ -354,6 +728,28 @@ var ru = {
354
728
  "table.colHeader": "\u0421\u0442\u043E\u043B\u0431\u0435\u0446 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432",
355
729
  "table.cellBackground": "\u0424\u043E\u043D \u044F\u0447\u0435\u0439\u043A\u0438",
356
730
  "table.delete": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0442\u0430\u0431\u043B\u0438\u0446\u0443",
731
+ "table.sort": "\u0421\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u043A\u0430",
732
+ "table.sortAsc": "\u0421\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0410 \u2192 \u042F, 1 \u2192 9",
733
+ "table.sortDesc": "\u0421\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u042F \u2192 \u0410, 9 \u2192 1",
734
+ "table.props": "\u0421\u0432\u043E\u0439\u0441\u0442\u0432\u0430 \u0442\u0430\u0431\u043B\u0438\u0446\u044B",
735
+ "table.width": "\u0428\u0438\u0440\u0438\u043D\u0430",
736
+ "table.widthHint": "\u041D\u0430\u043F\u0440\u0438\u043C\u0435\u0440, 100% \u0438\u043B\u0438 600px. \u041F\u0443\u0441\u0442\u043E \u2014 \u043F\u043E \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u043C\u0443.",
737
+ "table.invalidWidth": "\u0423\u043A\u0430\u0436\u0438\u0442\u0435 \u0448\u0438\u0440\u0438\u043D\u0443, \u043D\u0430\u043F\u0440\u0438\u043C\u0435\u0440 100% \u0438\u043B\u0438 600px",
738
+ "table.align": "\u0412\u044B\u0440\u0430\u0432\u043D\u0438\u0432\u0430\u043D\u0438\u0435 \u043D\u0430 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0435",
739
+ "table.alignDefault": "\u041F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E",
740
+ "table.alignCenter": "\u041F\u043E \u0446\u0435\u043D\u0442\u0440\u0443",
741
+ "table.alignRight": "\u0421\u043F\u0440\u0430\u0432\u0430",
742
+ "table.cellProps": "\u0421\u0432\u043E\u0439\u0441\u0442\u0432\u0430 \u044F\u0447\u0435\u0439\u043A\u0438",
743
+ "table.valign": "\u0412\u0435\u0440\u0442\u0438\u043A\u0430\u043B\u044C\u043D\u043E\u0435 \u0432\u044B\u0440\u0430\u0432\u043D\u0438\u0432\u0430\u043D\u0438\u0435",
744
+ "table.valignTop": "\u0421\u0432\u0435\u0440\u0445\u0443",
745
+ "table.valignMiddle": "\u041F\u043E \u0446\u0435\u043D\u0442\u0440\u0443",
746
+ "table.valignBottom": "\u0421\u043D\u0438\u0437\u0443",
747
+ "table.cellType": "\u0422\u0438\u043F \u044F\u0447\u0435\u0439\u043A\u0438",
748
+ "table.cellData": "\u041E\u0431\u044B\u0447\u043D\u0430\u044F",
749
+ "table.cellHeader": "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A",
750
+ "table.colWidth": "\u0428\u0438\u0440\u0438\u043D\u0430 \u0441\u0442\u043E\u043B\u0431\u0446\u0430, px",
751
+ "table.colWidthHint": "\u041F\u0443\u0441\u0442\u043E \u2014 \u043F\u043E \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u043C\u0443.",
752
+ "table.invalidColWidth": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043B\u043E \u043E\u0442 24 \u0434\u043E 4000",
357
753
  "slash.label": "\u041A\u043E\u043C\u0430\u043D\u0434\u044B",
358
754
  "slash.empty": "\u041D\u0435\u0442 \u043F\u043E\u0434\u0445\u043E\u0434\u044F\u0449\u0438\u0445 \u043A\u043E\u043C\u0430\u043D\u0434"
359
755
  };
@@ -382,8 +778,8 @@ import {
382
778
  ellipsis,
383
779
  emDash
384
780
  } from "prosemirror-inputrules";
385
- function buildInputRules(isAllowed = () => true) {
386
- const { nodes } = schema;
781
+ function buildInputRules(isAllowed = () => true, schema2 = schema) {
782
+ const { nodes } = schema2;
387
783
  const rules = [ellipsis, emDash];
388
784
  if (isAllowed("blockquote")) rules.push(wrappingInputRule(/^\s*>\s$/, nodes.blockquote));
389
785
  if (isAllowed("numlist")) {
@@ -411,13 +807,14 @@ import { keymap } from "prosemirror-keymap";
411
807
  import { splitListItem } from "prosemirror-schema-list";
412
808
  var mac = typeof navigator !== "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);
413
809
  var insertHardBreak = chainCommands(exitCode, (state, dispatch) => {
414
- dispatch?.(state.tr.replaceSelectionWith(schema.nodes.hard_break.create()).scrollIntoView());
810
+ dispatch?.(state.tr.replaceSelectionWith(nodesOf(state).hard_break.create()).scrollIntoView());
415
811
  return true;
416
812
  });
417
- function buildKeymap() {
813
+ var byName = (resolve, name) => (state, dispatch, view) => resolve(name)(state, dispatch, view);
814
+ function buildKeymap(resolve = (name) => commands[name]) {
418
815
  const keys = {
419
- "Mod-z": commands.undo,
420
- "Shift-Mod-z": commands.redo,
816
+ "Mod-z": byName(resolve, "undo"),
817
+ "Shift-Mod-z": byName(resolve, "redo"),
421
818
  "Mod-b": commands.bold,
422
819
  "Mod-i": commands.italic,
423
820
  "Mod-u": commands.underline,
@@ -440,16 +837,533 @@ function buildKeymap() {
440
837
  "Mod-Shift-j": commands.alignJustify,
441
838
  "Mod-\\": commands.clearFormatting,
442
839
  "Shift-Enter": insertHardBreak,
443
- Enter: splitListItem(schema.nodes.list_item),
840
+ Enter: (state, dispatch) => splitListItem(nodesOf(state).list_item)(state, dispatch),
444
841
  Tab: commands.indent,
445
842
  "Shift-Tab": commands.outdent
446
843
  };
447
- if (!mac) keys["Mod-y"] = commands.redo;
844
+ if (!mac) keys["Mod-y"] = byName(resolve, "redo");
448
845
  return [keymap(keys), keymap(baseKeymap)];
449
846
  }
450
847
 
451
848
  // src/paste.ts
452
- import { Plugin, PluginKey } from "prosemirror-state";
849
+ import { Slice } from "prosemirror-model";
850
+ import { Plugin as Plugin2, PluginKey } from "prosemirror-state";
851
+
852
+ // src/paste-office.ts
853
+ function detectPasteSource(html) {
854
+ if (/data-pm-slice=/.test(html)) return "nova";
855
+ if (/<google-sheets-html-origin|data-sheets-(root|value)/i.test(html)) return "google-sheets";
856
+ if (/id="docs-internal-guid-/.test(html)) return "google-docs";
857
+ if (/urn:schemas-microsoft-com:office:excel|ProgId"?\s+content="?Excel\.Sheet/i.test(html))
858
+ return "excel";
859
+ if (/urn:schemas-microsoft-com:office:word|class="?Mso|mso-list:|content="?Microsoft Word/i.test(
860
+ html
861
+ ))
862
+ return "word";
863
+ if (/class="[^"]*\b(TextRun|OutlineElement|EOP|SCXW\d+|BCX\d+)\b|data-ccp-props|paraid=/.test(html))
864
+ return "word-online";
865
+ if (/content="?LibreOffice|content="?OpenOffice/i.test(html)) return "libreoffice";
866
+ return "web";
867
+ }
868
+ function cleanPastedHTML(html, styles = "clean") {
869
+ const source = detectPasteSource(html);
870
+ if (source === "nova") return html;
871
+ const template = document.createElement("template");
872
+ template.innerHTML = html;
873
+ const root = document.createElement("div");
874
+ root.append(template.content);
875
+ inlineClassStyles(root);
876
+ removeJunk(root);
877
+ if (source === "word") convertWordLists(root);
878
+ if (source === "google-docs") unwrapGoogleDocsWrapper(root);
879
+ normalizeLists(root);
880
+ convertWordParagraphStyles(root);
881
+ root.querySelectorAll("[style]").forEach((el) => cleanStyle(el, styles));
882
+ if (styles === "clean") stripLayoutAttributes(root);
883
+ unwrapMeaningless(root);
884
+ removeBreaksBetweenBlocks(root);
885
+ normalizeEmptyParagraphs(root);
886
+ wrapCellContent(root);
887
+ return root.innerHTML;
888
+ }
889
+ function parseDeclarations(css) {
890
+ const out = /* @__PURE__ */ new Map();
891
+ for (const part of css.split(";")) {
892
+ const colon = part.indexOf(":");
893
+ if (colon < 0) continue;
894
+ const name = part.slice(0, colon).trim().toLowerCase();
895
+ const value = part.slice(colon + 1).trim().replace(/\s*!important$/i, "");
896
+ if (name && value) out.set(name, value);
897
+ }
898
+ return out;
899
+ }
900
+ function serializeDeclarations(decls) {
901
+ return [...decls].map(([name, value]) => `${name}: ${value}`).join("; ");
902
+ }
903
+ function inlineClassStyles(root) {
904
+ const sheets = [...root.querySelectorAll("style")].map((s) => s.textContent ?? "");
905
+ if (!sheets.length) return;
906
+ const rules = [];
907
+ const css = sheets.join("\n").replace(/\/\*[\s\S]*?\*\//g, "").replace(/<!--|-->/g, "");
908
+ for (const match of css.matchAll(/([^{}@]+)\{([^{}]*)\}/g)) {
909
+ const decls = parseDeclarations(match[2]);
910
+ for (const selector of match[1].split(",")) {
911
+ const m = selector.trim().match(/^([a-z][a-z0-9]*)?\.([\w-]+)$/i);
912
+ if (m) rules.push({ tag: (m[1] ?? "").toLowerCase(), cls: m[2], decls });
913
+ }
914
+ }
915
+ if (!rules.length) return;
916
+ root.querySelectorAll("[class]").forEach((el) => {
917
+ const classes = el.className.split(/\s+/).filter(Boolean);
918
+ const merged = /* @__PURE__ */ new Map();
919
+ for (const rule of rules) {
920
+ if (!classes.includes(rule.cls)) continue;
921
+ if (rule.tag && rule.tag !== el.tagName.toLowerCase()) continue;
922
+ rule.decls.forEach((value, name) => merged.set(name, value));
923
+ }
924
+ if (!merged.size) return;
925
+ parseDeclarations(el.getAttribute("style") ?? "").forEach(
926
+ (value, name) => merged.set(name, value)
927
+ );
928
+ el.setAttribute("style", serializeDeclarations(merged));
929
+ });
930
+ }
931
+ var DROP_TAGS = /^(STYLE|SCRIPT|META|LINK|TITLE|XML|HEAD|NOSCRIPT|TEMPLATE)$/;
932
+ function removeJunk(root) {
933
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
934
+ const comments = [];
935
+ while (walker.nextNode()) comments.push(walker.currentNode);
936
+ comments.forEach((c) => c.parentNode?.removeChild(c));
937
+ for (const el of [...root.querySelectorAll("*")]) {
938
+ if (!root.contains(el)) continue;
939
+ const tag = el.tagName.toUpperCase();
940
+ if (DROP_TAGS.test(tag)) {
941
+ el.remove();
942
+ continue;
943
+ }
944
+ if (tag.includes(":")) {
945
+ const prefix = tag.split(":")[0];
946
+ if (prefix === "O" || prefix === "V") el.remove();
947
+ else unwrap(el);
948
+ }
949
+ }
950
+ root.querySelectorAll("span.EOP").forEach((span) => {
951
+ if (/^\s*$/.test(span.textContent ?? "")) span.remove();
952
+ });
953
+ root.querySelectorAll("a").forEach((a) => {
954
+ const href = a.getAttribute("href") ?? "";
955
+ const redirect = href.match(/^https?:\/\/(www\.)?google\.[a-z.]+\/url\?(.*)$/i);
956
+ if (redirect) {
957
+ const target = new URLSearchParams(redirect[2]).get("q");
958
+ if (target) a.setAttribute("href", target);
959
+ }
960
+ if (!href || /^#_(ftn|edn|msocom|Toc|Ref)/i.test(href)) unwrap(a);
961
+ });
962
+ root.querySelectorAll('br[style*="page-break"]').forEach((br) => br.remove());
963
+ root.querySelectorAll(
964
+ '[style*="mso-element:footnote-list"], [style*="mso-element:comment-list"], [style*="mso-element:endnote-list"]'
965
+ ).forEach((el) => el.remove());
966
+ }
967
+ var ORDERED_MARKER = /^[([]?(\d+(\.\d+)*[.)\]]?|[a-z]{1,4}[.)\]])$/i;
968
+ function readWordListItem(el) {
969
+ const css = el.getAttribute("style") ?? "";
970
+ const match = css.match(/mso-list:\s*(l\d+)\s+level(\d+)/i);
971
+ if (!match) return null;
972
+ const markerEl = [...el.querySelectorAll("[style]")].find(
973
+ (s) => /mso-list:\s*Ignore/i.test(s.getAttribute("style") ?? "")
974
+ );
975
+ const marker = (markerEl?.textContent ?? "").replace(/\s+/g, "");
976
+ markerEl?.remove();
977
+ const ordered = ORDERED_MARKER.test(marker);
978
+ const { style, start } = ordered ? numbering(marker) : { style: bulletStyle(marker), start: 1 };
979
+ return {
980
+ el,
981
+ level: Math.max(1, Math.min(9, Number(match[2]))),
982
+ ordered,
983
+ start,
984
+ style
985
+ };
986
+ }
987
+ var ROMAN = /^(i|ii|iii|iv|v|vi|vii|viii|ix|x|xi|xii)$/i;
988
+ var ROMAN_VALUES = { i: 1, v: 5, x: 10 };
989
+ function romanToNumber(roman) {
990
+ let total = 0;
991
+ const chars = roman.toLowerCase();
992
+ for (let i = 0; i < chars.length; i++) {
993
+ const value = ROMAN_VALUES[chars[i]];
994
+ const next = ROMAN_VALUES[chars[i + 1] ?? ""] ?? 0;
995
+ total += value < next ? -value : value;
996
+ }
997
+ return total;
998
+ }
999
+ function numbering(marker) {
1000
+ const digits = marker.match(/\d+/);
1001
+ if (digits) return { style: null, start: Number(digits[0]) };
1002
+ const letters = marker.replace(/[^a-z]/gi, "");
1003
+ if (ROMAN.test(letters)) {
1004
+ return {
1005
+ style: letters === letters.toLowerCase() ? "lower-roman" : "upper-roman",
1006
+ start: romanToNumber(letters)
1007
+ };
1008
+ }
1009
+ const lower = letters === letters.toLowerCase();
1010
+ return {
1011
+ style: lower ? "lower-alpha" : "upper-alpha",
1012
+ start: letters.toLowerCase().charCodeAt(0) - 96
1013
+ };
1014
+ }
1015
+ function bulletStyle(marker) {
1016
+ if (marker === "o") return "circle";
1017
+ if (/^[§▪■]$/.test(marker)) return "square";
1018
+ return null;
1019
+ }
1020
+ function convertWordLists(root) {
1021
+ const candidates = [
1022
+ ...root.querySelectorAll("p, div, h1, h2, h3, h4, h5, h6")
1023
+ ].filter((el) => /mso-list:\s*l\d+\s+level\d+/i.test(el.getAttribute("style") ?? ""));
1024
+ for (const heading of candidates.filter((el) => /^H[1-6]$/.test(el.tagName))) {
1025
+ heading.querySelectorAll("[style]").forEach((s) => {
1026
+ if (!/mso-list:\s*Ignore/i.test(s.getAttribute("style") ?? "")) return;
1027
+ const marker = (s.textContent ?? "").replace(/\s+/g, "");
1028
+ s.replaceWith(s.ownerDocument.createTextNode(`${marker} `));
1029
+ });
1030
+ }
1031
+ const paragraphs = candidates.filter((el) => !/^H[1-6]$/.test(el.tagName));
1032
+ const done = /* @__PURE__ */ new Set();
1033
+ for (const first of paragraphs) {
1034
+ if (done.has(first)) continue;
1035
+ const run = [];
1036
+ let node = first;
1037
+ while (node instanceof HTMLElement && paragraphs.includes(node)) {
1038
+ const item = readWordListItem(node);
1039
+ if (!item) break;
1040
+ run.push(item);
1041
+ done.add(node);
1042
+ node = nextElement(node);
1043
+ }
1044
+ if (run.length) buildNestedList(run);
1045
+ }
1046
+ }
1047
+ function nextElement(el) {
1048
+ let next = el.nextSibling;
1049
+ while (next && next.nodeType === Node.TEXT_NODE && !next.textContent?.trim())
1050
+ next = next.nextSibling;
1051
+ return next instanceof Element ? next : null;
1052
+ }
1053
+ function buildNestedList(run) {
1054
+ const doc = run[0].el.ownerDocument;
1055
+ const anchor = run[0].el;
1056
+ const stack = [];
1057
+ let top = null;
1058
+ for (const item of run) {
1059
+ while (stack.length && stack[stack.length - 1].level > item.level) stack.pop();
1060
+ let current = stack[stack.length - 1];
1061
+ if (!current || current.level < item.level) {
1062
+ const list = doc.createElement(item.ordered ? "ol" : "ul");
1063
+ if (item.ordered && item.start !== 1) list.setAttribute("start", String(item.start));
1064
+ if (item.style) list.style.listStyleType = item.style;
1065
+ if (current) {
1066
+ const parentItem = current.list.lastElementChild ?? current.list.appendChild(doc.createElement("li"));
1067
+ parentItem.appendChild(list);
1068
+ } else top = list;
1069
+ current = { list, level: item.level };
1070
+ stack.push(current);
1071
+ }
1072
+ const li = doc.createElement("li");
1073
+ const p = doc.createElement("p");
1074
+ while (item.el.firstChild) p.appendChild(item.el.firstChild);
1075
+ li.appendChild(p);
1076
+ current.list.appendChild(li);
1077
+ }
1078
+ anchor.replaceWith(top);
1079
+ run.slice(1).forEach((item) => item.el.remove());
1080
+ }
1081
+ function levelOf(li) {
1082
+ const raw = li.getAttribute("aria-level") ?? li.getAttribute("data-aria-level");
1083
+ const n = raw ? Number(raw) : NaN;
1084
+ return Number.isFinite(n) && n >= 1 ? Math.min(9, n) : null;
1085
+ }
1086
+ function normalizeLists(root) {
1087
+ root.querySelectorAll("div").forEach((div) => {
1088
+ const only = div.children.length === 1 ? div.firstElementChild : null;
1089
+ if (only && /^(UL|OL)$/.test(only.tagName) && !div.textContent?.replace(only.textContent ?? "", "").trim())
1090
+ unwrap(div);
1091
+ });
1092
+ root.querySelectorAll("ul > ul, ul > ol, ol > ul, ol > ol").forEach((list) => {
1093
+ const prev = list.previousElementSibling;
1094
+ if (prev?.tagName === "LI") prev.appendChild(list);
1095
+ });
1096
+ const lists = [...root.querySelectorAll("ul, ol")].filter(
1097
+ (l) => !l.parentElement?.closest("ul, ol") && l.querySelector("li[aria-level], li[data-aria-level]")
1098
+ );
1099
+ const done = /* @__PURE__ */ new Set();
1100
+ for (const first of lists) {
1101
+ if (done.has(first) || !root.contains(first)) continue;
1102
+ const run = [];
1103
+ let node = first;
1104
+ while (node && /^(UL|OL)$/.test(node.tagName)) {
1105
+ done.add(node);
1106
+ collectListItems(node, 1, run);
1107
+ const next = nextElement(node);
1108
+ if (node !== first) node.remove();
1109
+ node = next;
1110
+ }
1111
+ if (!run.length) continue;
1112
+ const placeholder = first.ownerDocument.createElement("div");
1113
+ first.replaceWith(placeholder);
1114
+ buildNestedListFromBlocks(run, placeholder);
1115
+ }
1116
+ }
1117
+ function collectListItems(list, depth, run) {
1118
+ for (const li of [...list.children]) {
1119
+ if (li.tagName !== "LI") continue;
1120
+ const level = levelOf(li) ?? depth;
1121
+ const nested = [...li.children].filter((c) => /^(UL|OL)$/.test(c.tagName));
1122
+ nested.forEach((n) => n.remove());
1123
+ const holder = li.ownerDocument.createElement("div");
1124
+ while (li.firstChild) holder.appendChild(li.firstChild);
1125
+ run.push({
1126
+ el: holder,
1127
+ level,
1128
+ ordered: list.tagName === "OL",
1129
+ start: Number(list.getAttribute("start") ?? 1) || 1
1130
+ });
1131
+ nested.forEach((n) => collectListItems(n, level + 1, run));
1132
+ }
1133
+ }
1134
+ function buildNestedListFromBlocks(run, placeholder) {
1135
+ const doc = placeholder.ownerDocument;
1136
+ const stack = [];
1137
+ let top = null;
1138
+ for (const item of run) {
1139
+ while (stack.length && stack[stack.length - 1].level > item.level) stack.pop();
1140
+ let current = stack[stack.length - 1];
1141
+ if (!current || current.level < item.level) {
1142
+ const list = doc.createElement(item.ordered ? "ol" : "ul");
1143
+ if (item.ordered && item.start !== 1 && !current)
1144
+ list.setAttribute("start", String(item.start));
1145
+ if (current) {
1146
+ const parentItem = current.list.lastElementChild ?? current.list.appendChild(doc.createElement("li"));
1147
+ parentItem.appendChild(list);
1148
+ } else top = list;
1149
+ current = { list, level: item.level };
1150
+ stack.push(current);
1151
+ }
1152
+ const li = doc.createElement("li");
1153
+ while (item.el.firstChild) li.appendChild(item.el.firstChild);
1154
+ current.list.appendChild(li);
1155
+ }
1156
+ placeholder.replaceWith(top);
1157
+ }
1158
+ function unwrapGoogleDocsWrapper(root) {
1159
+ root.querySelectorAll('[id^="docs-internal-guid-"]').forEach(unwrap);
1160
+ root.querySelectorAll('li[role="checkbox"]').forEach((li) => {
1161
+ li.removeAttribute("role");
1162
+ li.removeAttribute("aria-checked");
1163
+ });
1164
+ }
1165
+ function convertWordParagraphStyles(root) {
1166
+ root.querySelectorAll('p.MsoTitle, p[class*="Title"]').forEach((p) => {
1167
+ if (!/\bMsoTitle\b|^Title$/.test(p.className)) return;
1168
+ renameElement(p, "h1");
1169
+ });
1170
+ root.querySelectorAll('div.WordSection1, div[class^="WordSection"], div.Section1').forEach(unwrap);
1171
+ }
1172
+ var DEFAULT_TEXT_COLORS = /^(black|windowtext|auto|#000|#000000|rgb\(0,\s*0,\s*0\)|initial|inherit)$/i;
1173
+ var DEFAULT_BACKGROUNDS = /^(transparent|white|window|auto|none|#fff|#ffffff|rgba?\(255,\s*255,\s*255(,\s*1)?\)|rgba\(\d+,\s*\d+,\s*\d+,\s*0\)|initial|inherit)$/i;
1174
+ var CLEAN_DROP = /^(font|font-family|font-size|line-height|margin|margin-.+|padding|padding-.+|text-indent|letter-spacing|word-spacing|white-space|height|width|min-height|border|border-.+|tab-stops|layout-grid-mode|page-break-.+|break-.+|orphans|widows|direction|unicode-bidi|font-variant.*|text-transform)$/i;
1175
+ function cleanStyle(el, mode) {
1176
+ const decls = parseDeclarations(el.getAttribute("style") ?? "");
1177
+ const out = /* @__PURE__ */ new Map();
1178
+ decls.forEach((value, name) => {
1179
+ if (name.startsWith("mso-")) {
1180
+ if (name === "mso-highlight" && !DEFAULT_BACKGROUNDS.test(value) && !decls.has("background-color"))
1181
+ out.set("background-color", value);
1182
+ return;
1183
+ }
1184
+ if (name.startsWith("-webkit-") || name.startsWith("-moz-")) return;
1185
+ if (name === "background") {
1186
+ const color2 = value.split(/\s+/)[0];
1187
+ if (/^(#[0-9a-f]{3,8}|rgba?\([^)]*\)|[a-z]+)$/i.test(color2) && !out.has("background-color"))
1188
+ out.set("background-color", color2);
1189
+ return;
1190
+ }
1191
+ if (name === "text-decoration" || name === "text-decoration-line") {
1192
+ if (/underline/.test(value)) out.set("text-decoration", "underline");
1193
+ else if (/line-through/.test(value)) out.set("text-decoration", "line-through");
1194
+ return;
1195
+ }
1196
+ if (mode === "clean" && CLEAN_DROP.test(name)) return;
1197
+ if (mode === "clean" && name === "vertical-align" && /^(TD|TH)$/.test(el.tagName)) return;
1198
+ out.set(name, value);
1199
+ });
1200
+ const color = out.get("color");
1201
+ if (color && DEFAULT_TEXT_COLORS.test(color.trim()) && mode === "clean") out.delete("color");
1202
+ const background = out.get("background-color");
1203
+ if (background && DEFAULT_BACKGROUNDS.test(background.trim())) out.delete("background-color");
1204
+ if (out.get("font-weight") === "normal" && el.tagName !== "B") out.delete("font-weight");
1205
+ if (out.get("font-style") === "normal") out.delete("font-style");
1206
+ if (out.get("text-decoration") === "none") out.delete("text-decoration");
1207
+ if (out.get("vertical-align") === "baseline") out.delete("vertical-align");
1208
+ if (/^(left|start)$/i.test(out.get("text-align") ?? "")) out.delete("text-align");
1209
+ if (mode === "clean" && el.closest("a")) {
1210
+ out.delete("color");
1211
+ if (out.get("text-decoration") === "underline") out.delete("text-decoration");
1212
+ }
1213
+ if (out.size) el.setAttribute("style", serializeDeclarations(out));
1214
+ else el.removeAttribute("style");
1215
+ }
1216
+ function stripLayoutAttributes(root) {
1217
+ root.querySelectorAll("table, tr, td, th, col, colgroup").forEach((el) => {
1218
+ el.removeAttribute("width");
1219
+ el.removeAttribute("height");
1220
+ el.removeAttribute("valign");
1221
+ });
1222
+ }
1223
+ function unwrapMeaningless(root) {
1224
+ for (const el of [...root.querySelectorAll("span, font")].reverse()) {
1225
+ if (!root.contains(el)) continue;
1226
+ const hasFormatting = el.hasAttribute("style") || el.tagName === "FONT" && el.hasAttribute("color");
1227
+ if (!hasFormatting) unwrap(el);
1228
+ }
1229
+ root.querySelectorAll("[class]").forEach((el) => el.removeAttribute("class"));
1230
+ root.querySelectorAll("[lang]").forEach((el) => el.removeAttribute("lang"));
1231
+ root.querySelectorAll("[dir]").forEach((el) => {
1232
+ if (!/^rtl$/i.test(el.getAttribute("dir") ?? "")) el.removeAttribute("dir");
1233
+ });
1234
+ }
1235
+ var BLOCK = /^(P|DIV|H[1-6]|UL|OL|TABLE|BLOCKQUOTE|PRE|HR)$/;
1236
+ function removeBreaksBetweenBlocks(root) {
1237
+ root.querySelectorAll("br").forEach((br) => {
1238
+ const parent = br.parentElement;
1239
+ if (!parent || !(parent === root || parent.tagName === "DIV" || parent.tagName === "TD" || parent.tagName === "LI"))
1240
+ return;
1241
+ const prev = siblingElement(br, -1);
1242
+ const next = siblingElement(br, 1);
1243
+ if (prev && BLOCK.test(prev.tagName) || next && BLOCK.test(next.tagName) || !prev && !next && parent === root)
1244
+ br.remove();
1245
+ });
1246
+ }
1247
+ function siblingElement(node, dir) {
1248
+ let s = dir < 0 ? node.previousSibling : node.nextSibling;
1249
+ while (s && s.nodeType === Node.TEXT_NODE && !s.textContent?.trim())
1250
+ s = dir < 0 ? s.previousSibling : s.nextSibling;
1251
+ return s instanceof Element ? s : null;
1252
+ }
1253
+ function normalizeEmptyParagraphs(root) {
1254
+ root.querySelectorAll("p").forEach((p) => {
1255
+ if (p.children.length === 0 && /^\s*$/.test(p.textContent ?? "")) p.textContent = "";
1256
+ });
1257
+ }
1258
+ function wrapCellContent(root) {
1259
+ root.querySelectorAll("td, th").forEach((cell) => {
1260
+ const align = cell.style.textAlign;
1261
+ const hasBlock = [...cell.children].some((c) => BLOCK.test(c.tagName));
1262
+ if (!align || hasBlock || !cell.textContent?.trim()) return;
1263
+ const p = cell.ownerDocument.createElement("p");
1264
+ p.style.textAlign = align;
1265
+ while (cell.firstChild) p.appendChild(cell.firstChild);
1266
+ cell.appendChild(p);
1267
+ cell.style.removeProperty("text-align");
1268
+ if (!cell.getAttribute("style")) cell.removeAttribute("style");
1269
+ });
1270
+ }
1271
+ function unwrap(el) {
1272
+ const parent = el.parentNode;
1273
+ if (!parent) return;
1274
+ while (el.firstChild) parent.insertBefore(el.firstChild, el);
1275
+ parent.removeChild(el);
1276
+ }
1277
+ function renameElement(el, tag) {
1278
+ const next = el.ownerDocument.createElement(tag);
1279
+ for (const attr of [...el.attributes]) next.setAttribute(attr.name, attr.value);
1280
+ while (el.firstChild) next.appendChild(el.firstChild);
1281
+ el.replaceWith(next);
1282
+ return next;
1283
+ }
1284
+
1285
+ // src/paste-rtf.ts
1286
+ function groupEnd(rtf, start) {
1287
+ let depth = 0;
1288
+ for (let i = start; i < rtf.length; i++) {
1289
+ const ch = rtf[i];
1290
+ if (ch === "\\") {
1291
+ i++;
1292
+ continue;
1293
+ }
1294
+ if (ch === "{") depth++;
1295
+ else if (ch === "}") {
1296
+ depth--;
1297
+ if (depth === 0) return i;
1298
+ }
1299
+ }
1300
+ return -1;
1301
+ }
1302
+ function withoutNestedGroups(body) {
1303
+ let out = "";
1304
+ let depth = 0;
1305
+ for (let i = 0; i < body.length; i++) {
1306
+ const ch = body[i];
1307
+ if (ch === "\\") {
1308
+ if (depth === 0) out += ch + (body[i + 1] ?? "");
1309
+ i++;
1310
+ continue;
1311
+ }
1312
+ if (ch === "{") depth++;
1313
+ else if (ch === "}") depth--;
1314
+ else if (depth === 0) out += ch;
1315
+ }
1316
+ return out;
1317
+ }
1318
+ var MAX_IMAGE_BYTES = 20 * 1024 * 1024;
1319
+ function hexToBase64(hex) {
1320
+ if (hex.length % 2 !== 0 || hex.length / 2 > MAX_IMAGE_BYTES || !/^[0-9a-f]+$/i.test(hex))
1321
+ return null;
1322
+ let binary = "";
1323
+ for (let i = 0; i < hex.length; i += 2)
1324
+ binary += String.fromCharCode(parseInt(hex.slice(i, i + 2), 16));
1325
+ return btoa(binary);
1326
+ }
1327
+ function extractRtfImages(rtf) {
1328
+ const images = [];
1329
+ let from = 0;
1330
+ for (; ; ) {
1331
+ const start = rtf.indexOf("{\\pict", from);
1332
+ if (start < 0) break;
1333
+ const end = groupEnd(rtf, start);
1334
+ if (end < 0) break;
1335
+ from = end + 1;
1336
+ if (/\\nonshppict\s*$/.test(rtf.slice(Math.max(0, start - 16), start))) continue;
1337
+ const body = withoutNestedGroups(rtf.slice(start + 1, end));
1338
+ const type = /\\pngblip(?![a-z])/.test(body) ? "image/png" : /\\jpegblip(?![a-z])/.test(body) ? "image/jpeg" : null;
1339
+ if (!type) continue;
1340
+ const hex = body.replace(/\\[a-z]+-?\d* ?/gi, "").replace(/\s+/g, "");
1341
+ const base64 = hexToBase64(hex);
1342
+ if (!base64) continue;
1343
+ const head = atob(base64.slice(0, 12));
1344
+ const valid = type === "image/png" ? head.startsWith(String.fromCharCode(137) + "PNG") : head.charCodeAt(0) === 255 && head.charCodeAt(1) === 216;
1345
+ if (valid) images.push({ type, base64 });
1346
+ }
1347
+ return images;
1348
+ }
1349
+ function hasLocalFileImages(html) {
1350
+ return /<img[^>]+src=["']?file:/i.test(html);
1351
+ }
1352
+ function replaceLocalImages(html, images) {
1353
+ const template = document.createElement("template");
1354
+ template.innerHTML = html;
1355
+ const targets = [...template.content.querySelectorAll("img")].filter(
1356
+ (img) => /^file:/i.test(img.getAttribute("src") ?? "")
1357
+ );
1358
+ if (!targets.length || targets.length !== images.length) return html;
1359
+ targets.forEach((img, i) => {
1360
+ const image = images[i];
1361
+ img.setAttribute("src", `data:${image.type};base64,${image.base64}`);
1362
+ });
1363
+ return template.innerHTML;
1364
+ }
1365
+
1366
+ // src/paste.ts
453
1367
  var key = new PluginKey("nova-paste");
454
1368
  function htmlToPlainText(html) {
455
1369
  const template = document.createElement("template");
@@ -480,12 +1394,26 @@ function htmlToPlainText(html) {
480
1394
  }
481
1395
  function pastePlugin(editor) {
482
1396
  let reentrant = false;
483
- return new Plugin({
1397
+ return new Plugin2({
484
1398
  key,
485
1399
  props: {
1400
+ /**
1401
+ * Вставка в пустой абзац заменяет его целиком: иначе первый вставленный абзац «сливается» с
1402
+ * пустым и теряет своё оформление (выравнивание, интервал, тип блока). В непустой абзац —
1403
+ * как обычно: первый абзац продолжает текущий, как в Word.
1404
+ */
1405
+ transformPasted(slice, view) {
1406
+ const { selection } = view.state;
1407
+ const parent = selection.$from.parent;
1408
+ if (slice.openStart > 0 && selection.empty && parent.isTextblock && parent.content.size === 0 && slice.content.firstChild?.isBlock) {
1409
+ return new Slice(slice.content, 0, slice.openEnd);
1410
+ }
1411
+ return slice;
1412
+ },
486
1413
  transformPastedHTML(html) {
487
- const { pastePreprocess, pastePostprocess } = editor.options;
1414
+ const { pastePreprocess, pastePostprocess, pasteStyles } = editor.options;
488
1415
  let result = pastePreprocess ? pastePreprocess(html, editor) : html;
1416
+ result = cleanPastedHTML(result, pasteStyles ?? "clean");
489
1417
  if (pastePostprocess) {
490
1418
  const template = document.createElement("template");
491
1419
  template.innerHTML = result;
@@ -497,8 +1425,21 @@ function pastePlugin(editor) {
497
1425
  return result;
498
1426
  },
499
1427
  handlePaste(view, event, slice) {
500
- if (reentrant || !editor.isPasteAsText()) return false;
1428
+ if (reentrant) return false;
501
1429
  const html = event.clipboardData?.getData("text/html");
1430
+ if (!editor.isPasteAsText()) {
1431
+ const rtf = html && hasLocalFileImages(html) ? event.clipboardData?.getData("text/rtf") : "";
1432
+ if (!html || !rtf || !editor.isAllowed("image")) return false;
1433
+ const withImages = replaceLocalImages(html, extractRtfImages(rtf));
1434
+ if (withImages === html) return false;
1435
+ reentrant = true;
1436
+ try {
1437
+ view.pasteHTML(withImages, event);
1438
+ } finally {
1439
+ reentrant = false;
1440
+ }
1441
+ return true;
1442
+ }
502
1443
  const text = html ? htmlToPlainText(html) : event.clipboardData?.getData("text/plain") || slice.content.textBetween(0, slice.content.size, "\n\n");
503
1444
  if (!text) return false;
504
1445
  reentrant = true;
@@ -514,7 +1455,9 @@ function pastePlugin(editor) {
514
1455
  }
515
1456
 
516
1457
  // src/parser.ts
517
- import { DOMParser } from "prosemirror-model";
1458
+ import {
1459
+ DOMParser
1460
+ } from "prosemirror-model";
518
1461
  var CELL_BG_ATTR = "data-nova-cell-bg";
519
1462
  function preprocessDOM(root) {
520
1463
  root.querySelectorAll("td, th").forEach((cell) => {
@@ -535,7 +1478,16 @@ var NovaDOMParser = class extends DOMParser {
535
1478
  return super.parseSlice(dom, options);
536
1479
  }
537
1480
  };
538
- var novaParser = new NovaDOMParser(schema, DOMParser.fromSchema(schema).rules);
1481
+ var parsers = /* @__PURE__ */ new WeakMap();
1482
+ function parserFor(target) {
1483
+ let parser = parsers.get(target);
1484
+ if (!parser) {
1485
+ parser = new NovaDOMParser(target, DOMParser.fromSchema(target).rules);
1486
+ parsers.set(target, parser);
1487
+ }
1488
+ return parser;
1489
+ }
1490
+ var novaParser = parserFor(schema);
539
1491
 
540
1492
  // src/ui/menu.ts
541
1493
  function createMenu(entries, onDone, label) {
@@ -791,7 +1743,7 @@ function printContent(editor) {
791
1743
  style.textContent = PRINT_CSS;
792
1744
  doc.head.append(style);
793
1745
  doc.body.append(
794
- DOMSerializer.fromSchema(schema).serializeFragment(editor.view.state.doc.content, {
1746
+ DOMSerializer.fromSchema(editor.schema).serializeFragment(editor.view.state.doc.content, {
795
1747
  document: doc
796
1748
  })
797
1749
  );
@@ -861,7 +1813,7 @@ function registerMenuItems(editor) {
861
1813
 
862
1814
  // src/content-rules.ts
863
1815
  import { Fragment } from "prosemirror-model";
864
- import { Plugin as Plugin2, PluginKey as PluginKey2 } from "prosemirror-state";
1816
+ import { Plugin as Plugin3, PluginKey as PluginKey2 } from "prosemirror-state";
865
1817
  var ALIASES = {
866
1818
  b: "strong",
867
1819
  i: "em",
@@ -1063,7 +2015,8 @@ var ContentRules = class {
1063
2015
  }
1064
2016
  /** Привести узел к правилам. Возвращает 0…n узлов (запрещённый блок может «раствориться»). */
1065
2017
  normalize(node) {
1066
- const { nodes } = schema;
2018
+ const schema2 = node.type.schema;
2019
+ const { nodes } = schema2;
1067
2020
  if (node.isText) {
1068
2021
  const marks2 = node.marks.filter((m) => this.markAllowed(m));
1069
2022
  return [marks2.length === node.marks.length ? node : node.mark(marks2)];
@@ -1080,7 +2033,7 @@ var ContentRules = class {
1080
2033
  )
1081
2034
  ];
1082
2035
  case nodes.hard_break:
1083
- return this.isTagAllowed("br") ? [node.mark(marks)] : [schema.text(" ", marks)];
2036
+ return this.isTagAllowed("br") ? [node.mark(marks)] : [schema2.text(" ", marks)];
1084
2037
  case nodes.horizontal_rule:
1085
2038
  return this.isTagAllowed("hr") ? [node] : [];
1086
2039
  }
@@ -1105,11 +2058,15 @@ var ContentRules = class {
1105
2058
  return this.isTagAllowed("blockquote") ? make() : asBlocks(children);
1106
2059
  case nodes.code_block:
1107
2060
  if (this.isTagAllowed("pre")) return make();
1108
- return node.textContent.split("\n").map((line) => nodes.paragraph.create(null, line ? schema.text(line) : null));
2061
+ return node.textContent.split("\n").map((line) => nodes.paragraph.create(null, line ? schema2.text(line) : null));
1109
2062
  case nodes.bullet_list:
1110
- return this.isTagAllowed("ul") ? make() : flattenItems(children);
1111
2063
  case nodes.ordered_list:
1112
- return this.isTagAllowed("ol") ? make() : flattenItems(children);
2064
+ if (!this.isTagAllowed(node.type === nodes.bullet_list ? "ul" : "ol"))
2065
+ return flattenItems(children);
2066
+ return make(node.type, {
2067
+ ...node.attrs,
2068
+ ...this.isStyleAllowed("list-style-type") ? {} : { listStyle: null }
2069
+ });
1113
2070
  case nodes.table:
1114
2071
  return this.isTagAllowed("table") ? make() : flattenTable(children);
1115
2072
  case nodes.table_header:
@@ -1131,14 +2088,16 @@ var ContentRules = class {
1131
2088
  /** Нормализовать документ целиком (начальное содержимое). */
1132
2089
  normalizeDoc(doc) {
1133
2090
  const content = this.normalizeChildren(doc.content);
1134
- return doc.type.createAndFill(null, content.size ? content : schema.nodes.paragraph.create());
2091
+ const schema2 = doc.type.schema;
2092
+ return doc.type.createAndFill(null, content.size ? content : schema2.nodes.paragraph.create());
1135
2093
  }
1136
2094
  };
1137
2095
  function asBlocks(fragment) {
1138
2096
  const out = [];
1139
2097
  let inline = [];
1140
2098
  const flush = () => {
1141
- if (inline.length) out.push(schema.nodes.paragraph.create(null, inline));
2099
+ if (inline.length)
2100
+ out.push(inline[0].type.schema.nodes.paragraph.create(null, inline));
1142
2101
  inline = [];
1143
2102
  };
1144
2103
  fragment.forEach((child) => {
@@ -1154,7 +2113,8 @@ function asBlocks(fragment) {
1154
2113
  function flattenItems(fragment) {
1155
2114
  const out = [];
1156
2115
  fragment.forEach((item) => {
1157
- if (item.type === schema.nodes.list_item) item.content.forEach((block) => out.push(block));
2116
+ if (item.type === item.type.schema.nodes.list_item)
2117
+ item.content.forEach((block) => out.push(block));
1158
2118
  else out.push(...asBlocks(Fragment.from(item)));
1159
2119
  });
1160
2120
  return out;
@@ -1166,7 +2126,7 @@ function flattenTable(fragment) {
1166
2126
  }
1167
2127
  var key2 = new PluginKey2("nova-content-rules");
1168
2128
  function contentRulesPlugin(rules) {
1169
- return new Plugin2({
2129
+ return new Plugin3({
1170
2130
  key: key2,
1171
2131
  appendTransaction(transactions, oldState, newState) {
1172
2132
  if (!transactions.some((tr2) => tr2.docChanged)) return null;
@@ -1188,7 +2148,7 @@ function contentRulesPlugin(rules) {
1188
2148
  for (const { from, to, nodes } of replacements.reverse()) {
1189
2149
  if (nodes.length) tr.replaceWith(from, to, nodes);
1190
2150
  else if (tr.doc.childCount > 1) tr.delete(from, to);
1191
- else tr.replaceWith(from, to, schema.nodes.paragraph.create());
2151
+ else tr.replaceWith(from, to, newState.schema.nodes.paragraph.create());
1192
2152
  }
1193
2153
  return tr.setMeta(
1194
2154
  "addToHistory",
@@ -1200,7 +2160,7 @@ function contentRulesPlugin(rules) {
1200
2160
 
1201
2161
  // src/search.ts
1202
2162
  import {
1203
- Plugin as Plugin3,
2163
+ Plugin as Plugin4,
1204
2164
  PluginKey as PluginKey3,
1205
2165
  TextSelection
1206
2166
  } from "prosemirror-state";
@@ -1248,7 +2208,7 @@ function indexFrom(matches, pos) {
1248
2208
  return i < 0 ? 0 : i;
1249
2209
  }
1250
2210
  function searchPlugin() {
1251
- return new Plugin3({
2211
+ return new Plugin4({
1252
2212
  key: searchKey,
1253
2213
  state: {
1254
2214
  init: () => EMPTY,
@@ -1545,12 +2505,15 @@ function toggleFullscreen(editor, value = !isFullscreen(editor)) {
1545
2505
  editor.root.classList.toggle("nova-fullscreen", value);
1546
2506
  document.documentElement.classList.toggle("nova-fullscreen-lock", value);
1547
2507
  editor.ui.closePopover();
2508
+ editor.updateUI();
1548
2509
  editor.focus();
1549
2510
  }
1550
2511
  function openPreview(editor) {
1551
2512
  const { t } = editor.ui;
1552
2513
  const content = h("div", { className: "nova-prosemirror nova-preview" });
1553
- content.append(DOMSerializer2.fromSchema(schema).serializeFragment(editor.view.state.doc.content));
2514
+ content.append(
2515
+ DOMSerializer2.fromSchema(editor.schema).serializeFragment(editor.view.state.doc.content)
2516
+ );
1554
2517
  content.querySelectorAll("a[href]").forEach((a) => {
1555
2518
  a.setAttribute("target", "_blank");
1556
2519
  a.setAttribute("rel", "noopener noreferrer");
@@ -1693,6 +2656,43 @@ function escapeAttr(value) {
1693
2656
  return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(NBSP, "&nbsp;");
1694
2657
  }
1695
2658
  var TAG_RE = /^[a-z][a-z0-9-]*$/i;
2659
+ var FORBIDDEN_TAGS = /* @__PURE__ */ new Set([
2660
+ "script",
2661
+ "style",
2662
+ "base",
2663
+ "link",
2664
+ "meta",
2665
+ "object",
2666
+ "embed",
2667
+ "applet",
2668
+ "frame",
2669
+ "frameset",
2670
+ "template",
2671
+ "noscript"
2672
+ ]);
2673
+ var LINK_ATTRS = /* @__PURE__ */ new Set(["href", "xlink:href", "action", "formaction", "cite"]);
2674
+ var RESOURCE_ATTRS = /* @__PURE__ */ new Set(["src", "poster", "data", "background"]);
2675
+ var UNSAFE_CSS = /url\s*\(|expression\s*\(|javascript:|@import|behavior\s*:|-moz-binding/i;
2676
+ function safeAttr(name, value) {
2677
+ const lower = name.toLowerCase();
2678
+ if (lower.startsWith("on")) return null;
2679
+ if (LINK_ATTRS.has(lower)) return isSafeLinkUrl(value) ? value : null;
2680
+ if (RESOURCE_ATTRS.has(lower)) return isSafeImageUrl(value) ? value : null;
2681
+ if (lower === "srcset") {
2682
+ const urls = value.split(",").map((part) => part.trim().split(/\s+/)[0] ?? "");
2683
+ return urls.every((url) => isSafeImageUrl(url)) ? value : null;
2684
+ }
2685
+ if (lower === "style") return UNSAFE_CSS.test(value) ? null : value;
2686
+ return value;
2687
+ }
2688
+ var reported = /* @__PURE__ */ new Set();
2689
+ function reportForbidden(tag) {
2690
+ if (reported.has(tag)) return;
2691
+ reported.add(tag);
2692
+ console.error(
2693
+ `[nova] toDOM produced <${tag}>, which is not allowed in output; the tag was dropped`
2694
+ );
2695
+ }
1696
2696
  var ATTR_RE = /^[a-z_:][a-z0-9_.:-]*$/i;
1697
2697
  function renderSpec(spec) {
1698
2698
  if (typeof spec === "string") return { open: "", close: "", hole: false, html: escapeText(spec) };
@@ -1702,6 +2702,8 @@ function renderSpec(spec) {
1702
2702
  const [rawTag, ...rest] = spec;
1703
2703
  const tag = rawTag.includes(" ") ? rawTag.split(" ")[1] : rawTag;
1704
2704
  if (!TAG_RE.test(tag)) throw new Error(`[nova] invalid tag in toDOM: ${tag}`);
2705
+ const forbidden = FORBIDDEN_TAGS.has(tag.toLowerCase());
2706
+ if (forbidden) reportForbidden(tag.toLowerCase());
1705
2707
  let attrs = "";
1706
2708
  let children = rest;
1707
2709
  const first = rest[0];
@@ -1710,11 +2712,13 @@ function renderSpec(spec) {
1710
2712
  if (value === null || value === void 0) continue;
1711
2713
  const attrName = name.includes(" ") ? name.split(" ")[1] : name;
1712
2714
  if (!ATTR_RE.test(attrName)) continue;
1713
- attrs += ` ${attrName}="${escapeAttr(String(value))}"`;
2715
+ const safe = safeAttr(attrName, String(value));
2716
+ if (safe === null) continue;
2717
+ attrs += ` ${attrName}="${escapeAttr(safe)}"`;
1714
2718
  }
1715
2719
  children = rest.slice(1);
1716
2720
  }
1717
- const open = `<${tag}${attrs}>`;
2721
+ const open = forbidden ? "" : `<${tag}${attrs}>`;
1718
2722
  if (VOID_ELEMENTS.has(tag.toLowerCase())) return { open, close: "", hole: false, html: open };
1719
2723
  let before = "";
1720
2724
  let after = "";
@@ -1737,6 +2741,9 @@ function renderSpec(spec) {
1737
2741
  before += inner.html;
1738
2742
  }
1739
2743
  }
2744
+ if (forbidden) {
2745
+ return { open: "", close: "", hole, html: "" };
2746
+ }
1740
2747
  const close = `</${tag}>`;
1741
2748
  return { open: open + before, close: after + close, hole, html: open + before + after + close };
1742
2749
  }
@@ -1806,7 +2813,7 @@ var validators = {
1806
2813
  };
1807
2814
  function setStyle(markName, value) {
1808
2815
  return (state, dispatch) => {
1809
- const type = schema.marks[markName];
2816
+ const type = marksOf(state)[markName];
1810
2817
  const valid = value === null ? null : validators[markName](value);
1811
2818
  if (value !== null && !valid) return false;
1812
2819
  const { empty } = state.selection;
@@ -1826,7 +2833,7 @@ function setStyle(markName, value) {
1826
2833
  };
1827
2834
  }
1828
2835
  function getStyle(state, markName) {
1829
- const type = schema.marks[markName];
2836
+ const type = marksOf(state)[markName];
1830
2837
  const { $from, empty } = state.selection;
1831
2838
  const marks = empty ? state.storedMarks ?? $from.marks() : $from.nodeAfter?.marks ?? $from.marks();
1832
2839
  const mark = type.isInSet(marks);
@@ -1840,7 +2847,7 @@ function setLineHeight(value) {
1840
2847
  const tr = state.tr;
1841
2848
  let applicable = false;
1842
2849
  state.doc.nodesBetween(from, to, (node, pos) => {
1843
- if (node.type === schema.nodes.paragraph || node.type === schema.nodes.heading) {
2850
+ if (node.type === nodesOf(state).paragraph || node.type === nodesOf(state).heading) {
1844
2851
  applicable = true;
1845
2852
  tr.setNodeMarkup(pos, void 0, { ...node.attrs, lineHeight: valid });
1846
2853
  }
@@ -2025,12 +3032,113 @@ function registerTableUi(editor) {
2025
3032
  }
2026
3033
  })
2027
3034
  });
3035
+ registry.addMenuButton("advtablesort", {
3036
+ icon: icons.sort,
3037
+ tooltip: t("table.sort"),
3038
+ isEnabled: (e) => e.can(sortTable("asc")),
3039
+ items: (e) => ["asc", "desc"].map((direction) => ({
3040
+ id: direction,
3041
+ label: t(direction === "asc" ? "table.sortAsc" : "table.sortDesc"),
3042
+ onSelect: () => e.exec(sortTable(direction, e.options.language))
3043
+ }))
3044
+ });
3045
+ registry.addButton("tableprops", {
3046
+ icon: icons.tableProps,
3047
+ tooltip: t("table.props"),
3048
+ isEnabled: (e) => isInTable(e.view.state),
3049
+ onAction: (e) => openTableProps(e)
3050
+ });
3051
+ registry.addButton("tablecellprops", {
3052
+ icon: icons.cellProps,
3053
+ tooltip: t("table.cellProps"),
3054
+ isEnabled: (e) => isInTable(e.view.state),
3055
+ onAction: (e) => openCellProps(e)
3056
+ });
2028
3057
  registry.addContextToolbar("table", {
2029
3058
  label: t("table.toolbar"),
2030
3059
  predicate: (e) => isInTable(e.view.state),
2031
3060
  anchor: (e) => tableRect(e),
2032
3061
  placement: "bottom-start",
2033
- items: "tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol | tablemergecells tablesplitcells | tablerowheader tablecolheader tablecellbackground | tabledelete"
3062
+ items: "tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol | tablemergecells tablesplitcells | tablerowheader tablecolheader tablecellbackground | advtablesort tablecellprops tableprops | tabledelete"
3063
+ });
3064
+ }
3065
+ function openTableProps(editor) {
3066
+ const { t } = editor.ui;
3067
+ const current = getTableProps(editor.view.state);
3068
+ if (!current) return;
3069
+ const width = textField({
3070
+ label: t("table.width"),
3071
+ hint: t("table.widthHint"),
3072
+ value: current.width ?? ""
3073
+ });
3074
+ const align = selectField({
3075
+ label: t("table.align"),
3076
+ value: current.align ?? "",
3077
+ options: [
3078
+ { value: "", label: t("table.alignDefault") },
3079
+ { value: "center", label: t("table.alignCenter") },
3080
+ { value: "right", label: t("table.alignRight") }
3081
+ ]
3082
+ });
3083
+ editor.ui.openDialog({
3084
+ title: t("table.props"),
3085
+ body: h("div", { className: "nova-form" }, width.el, align.el),
3086
+ submitLabel: t("dialog.save"),
3087
+ onSubmit: () => {
3088
+ const raw = width.input.value.trim().replace(/^(\d+(\.\d+)?)$/, "$1px");
3089
+ const props = {
3090
+ width: raw || null,
3091
+ align: align.select.value || null
3092
+ };
3093
+ return editor.exec(setTableProps(props)) || t("table.invalidWidth");
3094
+ }
3095
+ });
3096
+ }
3097
+ function openCellProps(editor) {
3098
+ const { t } = editor.ui;
3099
+ const current = getCellProps(editor.view.state);
3100
+ if (!current) return;
3101
+ const valign = selectField({
3102
+ label: t("table.valign"),
3103
+ value: current.valign ?? "",
3104
+ options: [
3105
+ { value: "", label: t("table.alignDefault") },
3106
+ { value: "top", label: t("table.valignTop") },
3107
+ { value: "middle", label: t("table.valignMiddle") },
3108
+ { value: "bottom", label: t("table.valignBottom") }
3109
+ ]
3110
+ });
3111
+ const type = selectField({
3112
+ label: t("table.cellType"),
3113
+ value: current.header ? "th" : "td",
3114
+ options: [
3115
+ { value: "td", label: t("table.cellData") },
3116
+ { value: "th", label: t("table.cellHeader") }
3117
+ ]
3118
+ });
3119
+ const width = textField({
3120
+ label: t("table.colWidth"),
3121
+ hint: t("table.colWidthHint"),
3122
+ value: current.width ? String(current.width) : ""
3123
+ });
3124
+ editor.ui.openDialog({
3125
+ title: t("table.cellProps"),
3126
+ body: h("div", { className: "nova-form" }, valign.el, type.el, width.el),
3127
+ submitLabel: t("dialog.save"),
3128
+ onSubmit: () => {
3129
+ const rawWidth = width.input.value.trim();
3130
+ const px = rawWidth ? Number(rawWidth.replace(/px$/i, "")) : null;
3131
+ if (px !== null && !(Number.isInteger(px) && px >= 24 && px <= 4e3))
3132
+ return t("table.invalidColWidth");
3133
+ editor.exec(
3134
+ setCellProps({
3135
+ valign: valign.select.value || null,
3136
+ header: type.select.value === "th",
3137
+ width: px
3138
+ })
3139
+ );
3140
+ return true;
3141
+ }
2034
3142
  });
2035
3143
  }
2036
3144
 
@@ -2120,7 +3228,7 @@ function registerBuiltins(editor) {
2120
3228
  isEnabled: (e) => e.can(command),
2121
3229
  ...isActive ? { isActive } : {}
2122
3230
  });
2123
- const markButton = (name, command, mark, svg) => commandButton(name, command, svg, () => isMarkActive(state(), schema.marks[mark]));
3231
+ const markButton = (name, command, mark, svg) => commandButton(name, command, svg, () => isMarkActive(state(), editor.schema.marks[mark]));
2124
3232
  commandButton("undo", "undo", icons.undo);
2125
3233
  commandButton("redo", "redo", icons.redo);
2126
3234
  markButton("bold", "bold", "bold", icons.bold);
@@ -2134,13 +3242,13 @@ function registerBuiltins(editor) {
2134
3242
  "bullist",
2135
3243
  "bulletList",
2136
3244
  icons.bulletList,
2137
- () => isNodeActive(state(), schema.nodes.bullet_list)
3245
+ () => isNodeActive(state(), editor.schema.nodes.bullet_list)
2138
3246
  );
2139
3247
  commandButton(
2140
3248
  "numlist",
2141
3249
  "orderedList",
2142
3250
  icons.orderedList,
2143
- () => isNodeActive(state(), schema.nodes.ordered_list)
3251
+ () => isNodeActive(state(), editor.schema.nodes.ordered_list)
2144
3252
  );
2145
3253
  commandButton("indent", "indent", icons.indent);
2146
3254
  commandButton("outdent", "outdent", icons.outdent);
@@ -2148,13 +3256,13 @@ function registerBuiltins(editor) {
2148
3256
  "blockquote",
2149
3257
  "blockquote",
2150
3258
  icons.blockquote,
2151
- () => isNodeActive(state(), schema.nodes.blockquote)
3259
+ () => isNodeActive(state(), editor.schema.nodes.blockquote)
2152
3260
  );
2153
3261
  commandButton(
2154
3262
  "codeblock",
2155
3263
  "codeBlock",
2156
3264
  icons.codeBlock,
2157
- () => isNodeActive(state(), schema.nodes.code_block)
3265
+ () => isNodeActive(state(), editor.schema.nodes.code_block)
2158
3266
  );
2159
3267
  commandButton("hr", "horizontalRule", icons.horizontalRule);
2160
3268
  commandButton("removeformat", "clearFormatting", icons.clearFormatting);
@@ -2192,8 +3300,8 @@ function registerBuiltins(editor) {
2192
3300
  ];
2193
3301
  const currentBlock = () => {
2194
3302
  const parent = state().selection.$from.parent;
2195
- if (parent.type === schema.nodes.heading) return `h${parent.attrs.level}`;
2196
- if (parent.type === schema.nodes.code_block) return "codeBlock";
3303
+ if (parent.type === editor.schema.nodes.heading) return `h${parent.attrs.level}`;
3304
+ if (parent.type === editor.schema.nodes.code_block) return "codeBlock";
2197
3305
  return "paragraph";
2198
3306
  };
2199
3307
  for (let level = 1; level <= 6; level++) {
@@ -2325,14 +3433,14 @@ function registerBuiltins(editor) {
2325
3433
  registry.addMenuButton("moreformats", {
2326
3434
  icon: icons.formatMore,
2327
3435
  tooltip: t("moreFormats"),
2328
- isActive: (e) => extraMarks.some(([, mark]) => isMarkActive(e.view.state, schema.marks[mark])),
3436
+ isActive: (e) => extraMarks.some(([, mark]) => isMarkActive(e.view.state, editor.schema.marks[mark])),
2329
3437
  items: (e) => [
2330
3438
  ...extraMarks.filter(([command]) => e.isAllowed(command)).map(([command, mark, svg]) => ({
2331
3439
  id: command,
2332
3440
  label: t(command),
2333
3441
  icon: svg,
2334
3442
  checkbox: true,
2335
- active: isMarkActive(e.view.state, schema.marks[mark]),
3443
+ active: isMarkActive(e.view.state, editor.schema.marks[mark]),
2336
3444
  disabled: !e.can(command),
2337
3445
  ...SHORTCUTS2[command] ? { shortcut: SHORTCUTS2[command] } : {},
2338
3446
  onSelect: () => e.exec(command)
@@ -2465,7 +3573,7 @@ function registerBuiltins(editor) {
2465
3573
  }
2466
3574
 
2467
3575
  // src/ui/link-bubble.ts
2468
- import { Plugin as Plugin4, PluginKey as PluginKey4 } from "prosemirror-state";
3576
+ import { Plugin as Plugin5, PluginKey as PluginKey4 } from "prosemirror-state";
2469
3577
 
2470
3578
  // src/ui/popover.ts
2471
3579
  var GAP = 6;
@@ -2546,7 +3654,7 @@ var Popover = class {
2546
3654
 
2547
3655
  // src/ui/link-bubble.ts
2548
3656
  function linkBubblePlugin(editor) {
2549
- return new Plugin4({
3657
+ return new Plugin5({
2550
3658
  key: new PluginKey4("nova-link-bubble"),
2551
3659
  view(view) {
2552
3660
  const { t } = editor.ui;
@@ -2594,7 +3702,7 @@ function linkBubblePlugin(editor) {
2594
3702
  hide();
2595
3703
  return;
2596
3704
  }
2597
- const range = markRange(state, schema.marks.link, state.selection.from);
3705
+ const range = markRange(state, marksOf(state).link, state.selection.from);
2598
3706
  if (!range) return hide();
2599
3707
  anchor.textContent = link.href;
2600
3708
  anchor.title = link.href;
@@ -2630,7 +3738,7 @@ function linkBubblePlugin(editor) {
2630
3738
  }
2631
3739
 
2632
3740
  // src/ui/context-toolbar.ts
2633
- import { NodeSelection, Plugin as Plugin5, PluginKey as PluginKey5 } from "prosemirror-state";
3741
+ import { NodeSelection as NodeSelection3, Plugin as Plugin6, PluginKey as PluginKey5 } from "prosemirror-state";
2634
3742
 
2635
3743
  // src/ui/toolbar.ts
2636
3744
  var defaultToolbar = "undo redo | blocks | bold italic underline strikethrough moreformats | forecolor backcolor | link image table | bullist numlist | align lineheight outdent indent | fontfamily fontsize | blockquote codeblock hr | removeformat | searchreplace preview code fullscreen help";
@@ -2693,6 +3801,7 @@ function createToolbar(editor, host, config, mode, { warnUnknown = true } = {})
2693
3801
  overflowPopover?.close();
2694
3802
  overflowPopover = null;
2695
3803
  };
3804
+ const offDialog = ui.onDialogOpen(closeOverflow);
2696
3805
  moreButton.addEventListener("click", (event) => {
2697
3806
  if (overflowPopover) return closeOverflow();
2698
3807
  moreButton.setAttribute("aria-expanded", "true");
@@ -2815,6 +3924,7 @@ function createToolbar(editor, host, config, mode, { warnUnknown = true } = {})
2815
3924
  },
2816
3925
  destroy: () => {
2817
3926
  resizeObserver?.disconnect();
3927
+ offDialog();
2818
3928
  closeOverflow();
2819
3929
  listeners.abort();
2820
3930
  host.replaceChildren();
@@ -2822,6 +3932,7 @@ function createToolbar(editor, host, config, mode, { warnUnknown = true } = {})
2822
3932
  };
2823
3933
  }
2824
3934
  function renderControl(editor, name, spec) {
3935
+ if (spec.type === "split") return renderSplit(editor, name, spec);
2825
3936
  const { ui } = editor;
2826
3937
  const el = h("button", {
2827
3938
  type: "button",
@@ -2903,10 +4014,37 @@ function renderControl(editor, name, spec) {
2903
4014
  };
2904
4015
  return { el, update };
2905
4016
  }
4017
+ function renderSplit(editor, name, spec) {
4018
+ const main = renderControl(editor, name, {
4019
+ type: "button",
4020
+ tooltip: spec.tooltip,
4021
+ onAction: spec.onAction,
4022
+ ...spec.icon ? { icon: spec.icon } : {},
4023
+ ...spec.text ? { text: spec.text } : {},
4024
+ ...spec.shortcut ? { shortcut: spec.shortcut } : {},
4025
+ ...spec.isActive ? { isActive: spec.isActive } : {},
4026
+ ...spec.isEnabled ? { isEnabled: spec.isEnabled } : {}
4027
+ });
4028
+ const more = renderControl(editor, `${name}-options`, {
4029
+ type: "menu",
4030
+ tooltip: `${spec.tooltip}: ${editor.ui.t("toolbar.options")}`,
4031
+ items: spec.items,
4032
+ ...spec.isEnabled ? { isEnabled: spec.isEnabled } : {}
4033
+ });
4034
+ more.el.classList.add("nova-tb-split-more");
4035
+ const el = h("span", { className: "nova-tb-split" }, main.el, more.el);
4036
+ return {
4037
+ el,
4038
+ update: () => {
4039
+ main.update();
4040
+ more.update();
4041
+ }
4042
+ };
4043
+ }
2906
4044
 
2907
4045
  // src/ui/context-toolbar.ts
2908
4046
  function contextToolbarPlugin(editor) {
2909
- return new Plugin5({
4047
+ return new Plugin6({
2910
4048
  key: new PluginKey5("nova-context-toolbar"),
2911
4049
  view(view) {
2912
4050
  const container = h("div", {
@@ -2943,7 +4081,7 @@ function contextToolbarPlugin(editor) {
2943
4081
  };
2944
4082
  const anchorRect = (spec) => {
2945
4083
  const { selection } = view.state;
2946
- if ((spec.position ?? "node") === "node" && selection instanceof NodeSelection) {
4084
+ if ((spec.position ?? "node") === "node" && selection instanceof NodeSelection3) {
2947
4085
  const dom = view.nodeDOM(selection.from);
2948
4086
  return dom?.getBoundingClientRect() ?? null;
2949
4087
  }
@@ -3041,7 +4179,7 @@ function focusContextToolbar(editor) {
3041
4179
  }
3042
4180
 
3043
4181
  // src/ui/image-view.ts
3044
- import { NodeSelection as NodeSelection2 } from "prosemirror-state";
4182
+ import { NodeSelection as NodeSelection4 } from "prosemirror-state";
3045
4183
  var MIN_WIDTH = 24;
3046
4184
  var ImageView = class {
3047
4185
  constructor(node, view, getPos, editor) {
@@ -3141,7 +4279,7 @@ var ImageView = class {
3141
4279
  width,
3142
4280
  height: Math.round(width * ratio)
3143
4281
  });
3144
- tr.setSelection(NodeSelection2.create(tr.doc, pos));
4282
+ tr.setSelection(NodeSelection4.create(tr.doc, pos));
3145
4283
  this.view.dispatch(tr);
3146
4284
  };
3147
4285
  handle.addEventListener("pointermove", onMove);
@@ -3151,7 +4289,7 @@ var ImageView = class {
3151
4289
  };
3152
4290
 
3153
4291
  // src/ui/autocompleter.ts
3154
- import { Plugin as Plugin6, PluginKey as PluginKey6 } from "prosemirror-state";
4292
+ import { Plugin as Plugin7, PluginKey as PluginKey6 } from "prosemirror-state";
3155
4293
  var MAX_QUERY = 30;
3156
4294
  function escapeRegExp(value) {
3157
4295
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -3273,7 +4411,7 @@ function autocompleterPlugin(editor) {
3273
4411
  renderItems(view);
3274
4412
  });
3275
4413
  };
3276
- return new Plugin6({
4414
+ return new Plugin7({
3277
4415
  key: new PluginKey6("nova-autocompleter"),
3278
4416
  view(view) {
3279
4417
  list = h("div", {
@@ -3511,6 +4649,9 @@ var Registry = class {
3511
4649
  addPanelButton(name, spec) {
3512
4650
  this.controls.set(name.toLowerCase(), { type: "panel", ...spec });
3513
4651
  }
4652
+ addSplitButton(name, spec) {
4653
+ this.controls.set(name.toLowerCase(), { type: "split", ...spec });
4654
+ }
3514
4655
  menuItems = /* @__PURE__ */ new Map();
3515
4656
  /** Пункт меню менюбара (аналог addMenuItem). */
3516
4657
  addMenuItem(name, spec) {
@@ -3528,7 +4669,7 @@ var Registry = class {
3528
4669
  const own = this.menuItems.get(name.toLowerCase());
3529
4670
  if (own) return own;
3530
4671
  const control = this.get(name);
3531
- if (control?.type !== "button") return void 0;
4672
+ if (control?.type !== "button" && control?.type !== "split") return void 0;
3532
4673
  return {
3533
4674
  text: control.tooltip,
3534
4675
  ...control.icon ? { icon: control.icon } : {},
@@ -3661,8 +4802,18 @@ var UiManager = class {
3661
4802
  get activePopover() {
3662
4803
  return this.popover;
3663
4804
  }
4805
+ dialogListeners = /* @__PURE__ */ new Set();
4806
+ /**
4807
+ * Подписаться на открытие диалога (вернёт отписку). Тулбар так закрывает панель «⋯»: иначе на узком
4808
+ * экране она оставалась открытой поверх текста после закрытия диалога, открытого из неё.
4809
+ */
4810
+ onDialogOpen(listener) {
4811
+ this.dialogListeners.add(listener);
4812
+ return () => this.dialogListeners.delete(listener);
4813
+ }
3664
4814
  openDialog(options) {
3665
4815
  this.closePopover();
4816
+ this.dialogListeners.forEach((listener) => listener());
3666
4817
  this.dialog?.close();
3667
4818
  const handle = openDialog({
3668
4819
  cancelLabel: this.t("dialog.cancel"),
@@ -3779,9 +4930,12 @@ var Editor = class {
3779
4930
  menubar;
3780
4931
  mode;
3781
4932
  pluginsByName = /* @__PURE__ */ new Map();
4933
+ commandOverrides = /* @__PURE__ */ new Map();
3782
4934
  cleanups = [];
3783
4935
  /** Ограничения контента (validElements/invalidElements/validStyles) или null — без ограничений. */
3784
4936
  contentRules;
4937
+ /** Схема документа этого редактора: базовая + узлы и марки синхронных плагинов. */
4938
+ schema;
3785
4939
  statusbar;
3786
4940
  searchBar;
3787
4941
  destroyed = false;
@@ -3852,22 +5006,25 @@ var Editor = class {
3852
5006
  const pluginPm = syncPlugins.flatMap((plugin) => this.collectPmPlugins(plugin));
3853
5007
  const hasRules = options.validElements !== void 0 || options.invalidElements !== void 0 || options.validStyles !== void 0;
3854
5008
  this.contentRules = hasRules ? new ContentRules(options) : null;
3855
- const initialDoc = parseContent(options.content ?? "");
5009
+ this.schema = this.buildSchema(syncPlugins);
5010
+ syncPlugins.forEach((plugin) => this.registerCommands(plugin));
5011
+ const initialDoc = parseContent(this.schema, options.content ?? "");
3856
5012
  const state = EditorState.create({
3857
5013
  doc: this.contentRules ? this.contentRules.normalizeDoc(initialDoc) : initialDoc,
3858
5014
  plugins: [
3859
5015
  // Первым: при открытом списке Enter/Tab/стрелки принадлежат автокомплитеру, а не раскладке клавиш.
3860
5016
  autocompleterPlugin(this),
3861
- buildInputRules((name) => this.isAllowed(name)),
5017
+ buildInputRules((name) => this.isAllowed(name), this.schema),
3862
5018
  editorKeys,
3863
5019
  // Таблицы до общей раскладки: Tab в таблице — следующая ячейка, а не отступ списка.
3864
5020
  ...tablePlugins(),
3865
5021
  searchPlugin(),
3866
- ...buildKeymap(),
3867
- history(),
5022
+ ...buildKeymap((name) => this.resolveCommand(name)),
5023
+ ...syncPlugins.some((plugin) => plugin.replaceHistory) ? [] : [history()],
3868
5024
  dropCursor({ color: "var(--nova-accent)", width: 2 }),
3869
5025
  gapCursor(),
3870
5026
  imageDropPastePlugin(this),
5027
+ embeddedImageUploadPlugin(this),
3871
5028
  pastePlugin(this),
3872
5029
  linkBubblePlugin(this),
3873
5030
  contextToolbarPlugin(this),
@@ -3878,6 +5035,7 @@ var Editor = class {
3878
5035
  });
3879
5036
  this.editable = options.editable ?? true;
3880
5037
  this.pasteAsText = options.pasteAsText ?? false;
5038
+ const handleTransaction = this.handleTransaction.bind(this);
3881
5039
  this.view = new EditorView(contentHost, {
3882
5040
  state,
3883
5041
  editable: () => this.editable,
@@ -3888,9 +5046,14 @@ var Editor = class {
3888
5046
  "aria-label": this.ui.t("editor.label"),
3889
5047
  ...options.placeholder ? { "data-placeholder": options.placeholder } : {}
3890
5048
  },
3891
- dispatchTransaction: (tr) => this.handleTransaction(tr),
5049
+ // ProseMirror вызывает dispatchTransaction с this = представление: плагины (например, синхронизация
5050
+ // совместного редактирования) могут отправить транзакцию ещё внутри конструктора EditorView,
5051
+ // когда this.view редактора не присвоен.
5052
+ dispatchTransaction: function(tr) {
5053
+ handleTransaction(tr, this);
5054
+ },
3892
5055
  // Тот же парсер для вставки, что и для setContent — одинаковая предобработка.
3893
- clipboardParser: novaParser,
5056
+ clipboardParser: parserFor(this.schema),
3894
5057
  nodeViews: {
3895
5058
  image: (node, view, getPos) => new ImageView(node, view, getPos, this)
3896
5059
  },
@@ -3934,6 +5097,30 @@ var Editor = class {
3934
5097
  hasPlugin(name) {
3935
5098
  return this.pluginsByName.has(name);
3936
5099
  }
5100
+ /**
5101
+ * Схема с узлами и марками плагинов. Конфликт имён — ошибка конфигурации: сообщаем и работаем
5102
+ * на базовой схеме, чтобы редактор всё равно открылся.
5103
+ */
5104
+ buildSchema(plugins) {
5105
+ const nodes = {};
5106
+ const marks = {};
5107
+ for (const plugin of plugins) {
5108
+ for (const [name, spec] of Object.entries(plugin.nodes ?? {})) {
5109
+ if (name in nodes) reportPluginError(`Node "${name}" is defined by several plugins`);
5110
+ else nodes[name] = spec;
5111
+ }
5112
+ for (const [name, spec] of Object.entries(plugin.marks ?? {})) {
5113
+ if (name in marks) reportPluginError(`Mark "${name}" is defined by several plugins`);
5114
+ else marks[name] = spec;
5115
+ }
5116
+ }
5117
+ try {
5118
+ return createSchema({ nodes, marks });
5119
+ } catch (error) {
5120
+ reportPluginError("Failed to build the document schema from plugins", error);
5121
+ return createSchema();
5122
+ }
5123
+ }
3937
5124
  collectPmPlugins(plugin) {
3938
5125
  try {
3939
5126
  return plugin.prosemirrorPlugins?.(this) ?? [];
@@ -3962,7 +5149,16 @@ var Editor = class {
3962
5149
  )
3963
5150
  );
3964
5151
  if (this.destroyed) return;
3965
- const loaded = results.filter((p) => !!p);
5152
+ const loaded = results.filter((p) => {
5153
+ if (!p) return false;
5154
+ if (p.nodes || p.marks) {
5155
+ reportPluginError(
5156
+ `Plugin "${p.name}" defines nodes or marks and cannot be loaded lazily; pass the plugin object instead`
5157
+ );
5158
+ return false;
5159
+ }
5160
+ return true;
5161
+ });
3966
5162
  const { ordered, errors } = orderPlugins(loaded, new Set(this.pluginsByName.keys()));
3967
5163
  errors.forEach((message) => reportPluginError(message));
3968
5164
  const extraPm = ordered.flatMap((plugin) => this.collectPmPlugins(plugin));
@@ -3970,9 +5166,20 @@ var Editor = class {
3970
5166
  const state = this.view.state;
3971
5167
  this.view.updateState(state.reconfigure({ plugins: [...state.plugins, ...extraPm] }));
3972
5168
  }
3973
- ordered.forEach((plugin) => this.setupPlugin(plugin));
5169
+ ordered.forEach((plugin) => {
5170
+ this.registerCommands(plugin);
5171
+ this.setupPlugin(plugin);
5172
+ });
3974
5173
  this.rebuildToolbar();
3975
5174
  }
5175
+ /**
5176
+ * Обновить состояние кнопок (нажата / доступна) без изменения документа — например, после того как
5177
+ * плагин переключил режим отображения. Изменения документа обновляют UI сами.
5178
+ */
5179
+ updateUI() {
5180
+ if (this.destroyed) return;
5181
+ this.toolbar?.update();
5182
+ }
3976
5183
  /** Перестроить тулбар (после регистрации новых кнопок плагинами). */
3977
5184
  rebuildToolbar() {
3978
5185
  if (!this.toolbar || this.destroyed) return;
@@ -3990,9 +5197,10 @@ var Editor = class {
3990
5197
  const extra = [...this.pluginsByName.values()].map((p) => p.toolbar).filter(Boolean);
3991
5198
  return extra.length ? `${defaultToolbar} | ${extra.join(" ")}` : defaultToolbar;
3992
5199
  }
3993
- handleTransaction(tr) {
3994
- const newState = this.view.state.apply(tr);
3995
- this.view.updateState(newState);
5200
+ handleTransaction(tr, view = this.view) {
5201
+ if (view.isDestroyed) return;
5202
+ view.updateState(view.state.apply(tr));
5203
+ if (!this.view) return;
3996
5204
  this.toolbar?.update();
3997
5205
  this.statusbar?.update(tr.docChanged);
3998
5206
  this.searchBar?.update();
@@ -4002,7 +5210,7 @@ var Editor = class {
4002
5210
  }
4003
5211
  updatePlaceholder() {
4004
5212
  const doc = this.view.state.doc;
4005
- const empty = doc.childCount === 1 && doc.firstChild?.type === schema.nodes.paragraph && doc.firstChild.content.size === 0;
5213
+ const empty = doc.childCount === 1 && doc.firstChild?.type === this.schema.nodes.paragraph && doc.firstChild.content.size === 0;
4006
5214
  this.view.dom.classList.toggle("nova-empty", empty);
4007
5215
  }
4008
5216
  // ---------- содержимое ----------
@@ -4018,7 +5226,7 @@ var Editor = class {
4018
5226
  }
4019
5227
  /** Заменить содержимое. По умолчанию попадает в историю undo. */
4020
5228
  setContent(content, { addToHistory = true } = {}) {
4021
- const doc = parseContent(content);
5229
+ const doc = parseContent(this.schema, content);
4022
5230
  const tr = this.view.state.tr.replaceWith(0, this.view.state.doc.content.size, doc.content);
4023
5231
  if (!addToHistory) tr.setMeta("addToHistory", false);
4024
5232
  this.view.dispatch(tr);
@@ -4028,15 +5236,24 @@ var Editor = class {
4028
5236
  }
4029
5237
  // ---------- команды ----------
4030
5238
  /** Выполнить именованную команду или произвольную ProseMirror-команду. */
5239
+ /** Команда по имени: переопределение плагина или встроенная. */
5240
+ resolveCommand(name) {
5241
+ return this.commandOverrides.get(name) ?? commands[name];
5242
+ }
5243
+ registerCommands(plugin) {
5244
+ for (const [name, command] of Object.entries(plugin.commands ?? {})) {
5245
+ if (command) this.commandOverrides.set(name, command);
5246
+ }
5247
+ }
4031
5248
  exec(command) {
4032
- const cmd = typeof command === "string" ? commands[command] : command;
5249
+ const cmd = typeof command === "string" ? this.resolveCommand(command) : command;
4033
5250
  const result = cmd(this.view.state, this.view.dispatch, this.view);
4034
5251
  if (result) this.view.focus();
4035
5252
  return result;
4036
5253
  }
4037
5254
  /** Можно ли выполнить команду в текущем состоянии (для disabled-кнопок). */
4038
5255
  can(command) {
4039
- const cmd = typeof command === "string" ? commands[command] : command;
5256
+ const cmd = typeof command === "string" ? this.resolveCommand(command) : command;
4040
5257
  return cmd(this.view.state, void 0, this.view);
4041
5258
  }
4042
5259
  /** Активна ли именованная команда в текущем выделении (для своих кнопок тулбара). */
@@ -4111,13 +5328,13 @@ var Editor = class {
4111
5328
  function reportPluginError(message, error) {
4112
5329
  console.error(`[nova] ${message}`, ...error === void 0 ? [] : [error]);
4113
5330
  }
4114
- function parseContent(content) {
4115
- if (typeof content !== "string") return PMNode.fromJSON(schema, content);
5331
+ function parseContent(schema2, content) {
5332
+ if (typeof content !== "string") return PMNode.fromJSON(schema2, content);
4116
5333
  const container = document.createElement("div");
4117
5334
  const template = document.createElement("template");
4118
5335
  template.innerHTML = content;
4119
5336
  container.appendChild(template.content);
4120
- return novaParser.parse(container);
5337
+ return parserFor(schema2).parse(container);
4121
5338
  }
4122
5339
  function createEditor(options) {
4123
5340
  return new Editor(options);
@@ -4134,6 +5351,7 @@ export {
4134
5351
  commands,
4135
5352
  countWords,
4136
5353
  createEditor,
5354
+ createSchema,
4137
5355
  createTable,
4138
5356
  createTranslator,
4139
5357
  cssValue,
@@ -4168,6 +5386,8 @@ export {
4168
5386
  isPluginRegistered,
4169
5387
  isSafeImageUrl,
4170
5388
  isSafeLinkUrl,
5389
+ marksOf,
5390
+ nodesOf,
4171
5391
  normalizeUrl,
4172
5392
  openHelp,
4173
5393
  openImageAltDialog,
@@ -4176,6 +5396,7 @@ export {
4176
5396
  openPreview,
4177
5397
  openSourceCode,
4178
5398
  parseToolbar,
5399
+ parserFor,
4179
5400
  printContent,
4180
5401
  rankSlashCommands,
4181
5402
  registerLanguage,