@novaprose/core 0.5.3 → 0.7.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 (137) hide show
  1. package/README.md +57 -20
  2. package/dist/{advlist-FH3K3AAQ.js → advlist-5FNKPLUX.js} +11 -20
  3. package/dist/advlist-5FNKPLUX.js.map +1 -0
  4. package/dist/{autolink-IDJWAL2V.js → autolink-45LTODWB.js} +7 -4
  5. package/dist/{autolink-IDJWAL2V.js.map → autolink-45LTODWB.js.map} +1 -1
  6. package/dist/{autoresize-4ZEPQCHP.js → autoresize-UB3GOA6D.js} +2 -2
  7. package/dist/{autosave-DH7SO4UQ.js → autosave-GMWJ5BPE.js} +7 -11
  8. package/dist/autosave-GMWJ5BPE.js.map +1 -0
  9. package/dist/{charmap-F7EVJ56K.js → charmap-2GC7LF7G.js} +7 -12
  10. package/dist/charmap-2GC7LF7G.js.map +1 -0
  11. package/dist/{chunk-MOO4PJGI.js → chunk-5AW2HHG6.js} +16 -1
  12. package/dist/chunk-5AW2HHG6.js.map +1 -0
  13. package/dist/{chunk-55LD2TT2.js → chunk-DWZLSZDG.js} +1550 -935
  14. package/dist/chunk-DWZLSZDG.js.map +1 -0
  15. package/dist/{chunk-YZPJQB3I.js → chunk-FCMZ7TUQ.js} +308 -34
  16. package/dist/chunk-FCMZ7TUQ.js.map +1 -0
  17. package/dist/{chunk-6GWG2BLC.js → chunk-HPLT3XRZ.js} +1 -1
  18. package/dist/chunk-HPLT3XRZ.js.map +1 -0
  19. package/dist/{chunk-HZRIBOPW.js → chunk-JPJVTB45.js} +38 -2
  20. package/dist/chunk-JPJVTB45.js.map +1 -0
  21. package/dist/{chunk-6AL2IS6V.js → chunk-KPE3QRPB.js} +206 -404
  22. package/dist/chunk-KPE3QRPB.js.map +1 -0
  23. package/dist/chunk-KWXFL4WS.js +174 -0
  24. package/dist/chunk-KWXFL4WS.js.map +1 -0
  25. package/dist/chunk-ND2CWNVG.js +51 -0
  26. package/dist/chunk-ND2CWNVG.js.map +1 -0
  27. package/dist/chunk-PVFKXRID.js +27 -0
  28. package/dist/chunk-PVFKXRID.js.map +1 -0
  29. package/dist/chunk-R2UMUCVI.js +351 -0
  30. package/dist/chunk-R2UMUCVI.js.map +1 -0
  31. package/dist/{chunk-GHEFKKRC.js → chunk-T3GY6IVK.js} +41 -24
  32. package/dist/chunk-T3GY6IVK.js.map +1 -0
  33. package/dist/{comments-panel-FYJE3U64.js → comments-panel-HXMWSRAW.js} +5 -3
  34. package/dist/comments-panel-HXMWSRAW.js.map +1 -0
  35. package/dist/{directionality-MF5HDXH3.js → directionality-5JLWQGP2.js} +13 -11
  36. package/dist/directionality-5JLWQGP2.js.map +1 -0
  37. package/dist/editor-CXkltf1R.d.ts +1886 -0
  38. package/dist/editor-CgSBFTke.d.cts +1886 -0
  39. package/dist/{emoticons-SONBUCFV.js → emoticons-ZD6ZRIWG.js} +7 -12
  40. package/dist/emoticons-ZD6ZRIWG.js.map +1 -0
  41. package/dist/form-dialog-QH6KAERD.js +180 -0
  42. package/dist/form-dialog-QH6KAERD.js.map +1 -0
  43. package/dist/html-rules-api-D3fKQi-R.d.cts +40 -0
  44. package/dist/html-rules-api-D3fKQi-R.d.ts +40 -0
  45. package/dist/html-rules.cjs +480 -0
  46. package/dist/html-rules.cjs.map +1 -0
  47. package/dist/html-rules.d.cts +87 -0
  48. package/dist/html-rules.d.ts +87 -0
  49. package/dist/html-rules.js +413 -0
  50. package/dist/html-rules.js.map +1 -0
  51. package/dist/i18n/de.cjs +324 -0
  52. package/dist/i18n/de.cjs.map +1 -0
  53. package/dist/i18n/de.d.cts +9 -0
  54. package/dist/i18n/de.d.ts +9 -0
  55. package/dist/i18n/de.js +303 -0
  56. package/dist/i18n/de.js.map +1 -0
  57. package/dist/i18n/es.cjs +324 -0
  58. package/dist/i18n/es.cjs.map +1 -0
  59. package/dist/i18n/es.d.cts +9 -0
  60. package/dist/i18n/es.d.ts +9 -0
  61. package/dist/i18n/es.js +303 -0
  62. package/dist/i18n/es.js.map +1 -0
  63. package/dist/i18n/fr.cjs +324 -0
  64. package/dist/i18n/fr.cjs.map +1 -0
  65. package/dist/i18n/fr.d.cts +9 -0
  66. package/dist/i18n/fr.d.ts +9 -0
  67. package/dist/i18n/fr.js +303 -0
  68. package/dist/i18n/fr.js.map +1 -0
  69. package/dist/i18n/it.cjs +324 -0
  70. package/dist/i18n/it.cjs.map +1 -0
  71. package/dist/i18n/it.d.cts +9 -0
  72. package/dist/i18n/it.d.ts +9 -0
  73. package/dist/i18n/it.js +303 -0
  74. package/dist/i18n/it.js.map +1 -0
  75. package/dist/i18n/pt-BR.cjs +324 -0
  76. package/dist/i18n/pt-BR.cjs.map +1 -0
  77. package/dist/i18n/pt-BR.d.cts +9 -0
  78. package/dist/i18n/pt-BR.d.ts +9 -0
  79. package/dist/i18n/pt-BR.js +303 -0
  80. package/dist/i18n/pt-BR.js.map +1 -0
  81. package/dist/i18n/ru.cjs +324 -0
  82. package/dist/i18n/ru.cjs.map +1 -0
  83. package/dist/i18n/ru.d.cts +10 -0
  84. package/dist/i18n/ru.d.ts +10 -0
  85. package/dist/i18n/ru.js +303 -0
  86. package/dist/i18n/ru.js.map +1 -0
  87. package/dist/index-C603bU6r.d.cts +216 -0
  88. package/dist/index-C603bU6r.d.ts +216 -0
  89. package/dist/index.cjs +3422 -1179
  90. package/dist/index.cjs.map +1 -1
  91. package/dist/index.d.cts +50 -1555
  92. package/dist/index.d.ts +50 -1555
  93. package/dist/index.js +278 -147
  94. package/dist/index.js.map +1 -1
  95. package/dist/{insertdatetime-X2T4ZY6R.js → insertdatetime-CRO7TJAQ.js} +10 -16
  96. package/dist/insertdatetime-CRO7TJAQ.js.map +1 -0
  97. package/dist/markdown.cjs +273 -0
  98. package/dist/markdown.cjs.map +1 -0
  99. package/dist/markdown.d.cts +23 -0
  100. package/dist/markdown.d.ts +23 -0
  101. package/dist/markdown.js +241 -0
  102. package/dist/markdown.js.map +1 -0
  103. package/dist/{nonbreaking-PP4KIJSR.js → nonbreaking-66LFZV2W.js} +8 -7
  104. package/dist/nonbreaking-66LFZV2W.js.map +1 -0
  105. package/dist/paste-office-F3QW4WWO.js +440 -0
  106. package/dist/paste-office-F3QW4WWO.js.map +1 -0
  107. package/dist/{quickbars-3WKHLKAR.js → quickbars-7E2QRS7J.js} +13 -9
  108. package/dist/quickbars-7E2QRS7J.js.map +1 -0
  109. package/dist/{revisionhistory-FYRVDGRA.js → revisionhistory-DXE7KU4R.js} +18 -32
  110. package/dist/revisionhistory-DXE7KU4R.js.map +1 -0
  111. package/dist/table-SSNABG5W.js +301 -0
  112. package/dist/table-SSNABG5W.js.map +1 -0
  113. package/dist/{visualblocks-NPTMWFXD.js → visualblocks-6DLBXYOA.js} +8 -7
  114. package/dist/visualblocks-6DLBXYOA.js.map +1 -0
  115. package/package.json +45 -5
  116. package/src/style.css +291 -29
  117. package/dist/advlist-FH3K3AAQ.js.map +0 -1
  118. package/dist/autosave-DH7SO4UQ.js.map +0 -1
  119. package/dist/charmap-F7EVJ56K.js.map +0 -1
  120. package/dist/chunk-55LD2TT2.js.map +0 -1
  121. package/dist/chunk-6AL2IS6V.js.map +0 -1
  122. package/dist/chunk-6GWG2BLC.js.map +0 -1
  123. package/dist/chunk-6RJENZXT.js +0 -104
  124. package/dist/chunk-6RJENZXT.js.map +0 -1
  125. package/dist/chunk-GHEFKKRC.js.map +0 -1
  126. package/dist/chunk-HZRIBOPW.js.map +0 -1
  127. package/dist/chunk-MOO4PJGI.js.map +0 -1
  128. package/dist/chunk-YZPJQB3I.js.map +0 -1
  129. package/dist/comments-panel-FYJE3U64.js.map +0 -1
  130. package/dist/directionality-MF5HDXH3.js.map +0 -1
  131. package/dist/emoticons-SONBUCFV.js.map +0 -1
  132. package/dist/insertdatetime-X2T4ZY6R.js.map +0 -1
  133. package/dist/nonbreaking-PP4KIJSR.js.map +0 -1
  134. package/dist/quickbars-3WKHLKAR.js.map +0 -1
  135. package/dist/revisionhistory-FYRVDGRA.js.map +0 -1
  136. package/dist/visualblocks-NPTMWFXD.js.map +0 -1
  137. /package/dist/{autoresize-4ZEPQCHP.js.map → autoresize-UB3GOA6D.js.map} +0 -0
@@ -1,858 +1,494 @@
1
1
  import {
2
- createTableGridPanel,
3
2
  embeddedImageUploadPlugin,
4
- getCellProps,
3
+ exitImageCaption,
5
4
  getSelectedImage,
6
- getTableProps,
7
- hasHeaderColumn,
8
- hasHeaderRow,
5
+ hasImageCaption,
9
6
  imageDropPastePlugin,
10
- insertTable,
11
- isInTable,
12
7
  openDialog,
13
8
  openImageAltDialog,
14
9
  openImageDialog,
15
10
  openLinkDialog,
16
11
  removeLink,
17
12
  selectField,
18
- setCellBackground,
19
- setCellProps,
20
13
  setImageAttrs,
21
14
  setImageWidthFraction,
15
+ textField,
16
+ toggleImageCaption
17
+ } from "./chunk-KPE3QRPB.js";
18
+ import {
19
+ commands,
20
+ getActiveAlign,
21
+ getLinkAt,
22
+ isCommandActive,
23
+ isMarkActive,
24
+ isNodeActive,
25
+ listIndent,
26
+ listOutdent,
27
+ markRange,
28
+ marksOf,
29
+ nodesOf
30
+ } from "./chunk-T3GY6IVK.js";
31
+ import {
32
+ createTableGridPanel,
33
+ getCellProps,
34
+ getTableProps,
35
+ hasHeaderColumn,
36
+ hasHeaderRow,
37
+ insertTable,
38
+ loadTables,
39
+ setCellBackground,
40
+ setCellProps,
22
41
  setTableProps,
23
42
  sortTable,
24
43
  tableCommands,
25
- tablePlugins,
26
- tableRect,
27
- textField
28
- } from "./chunk-6AL2IS6V.js";
44
+ tableRect
45
+ } from "./chunk-KWXFL4WS.js";
29
46
  import {
47
+ ALIGNMENTS,
48
+ classAttr,
30
49
  createSchema,
31
50
  cssValue,
32
51
  imageSize,
52
+ isInTable,
33
53
  schema
34
- } from "./chunk-YZPJQB3I.js";
54
+ } from "./chunk-FCMZ7TUQ.js";
55
+ import {
56
+ createTranslator
57
+ } from "./chunk-R2UMUCVI.js";
58
+ import {
59
+ icons
60
+ } from "./chunk-5AW2HHG6.js";
61
+ import {
62
+ loadPlugin,
63
+ orderPlugins,
64
+ resolveEntries
65
+ } from "./chunk-HPLT3XRZ.js";
35
66
  import {
67
+ FOCUSABLE,
68
+ activeElement,
36
69
  formatShortcut,
37
70
  h,
38
71
  icon,
72
+ isRtl,
73
+ listenDocument,
74
+ logicalKey,
39
75
  uniqueId
40
- } from "./chunk-HZRIBOPW.js";
76
+ } from "./chunk-JPJVTB45.js";
41
77
  import {
42
- icons
43
- } from "./chunk-MOO4PJGI.js";
78
+ OWN_STYLE,
79
+ htmlRulesFor,
80
+ safeAttr
81
+ } from "./chunk-ND2CWNVG.js";
44
82
  import {
45
- commands,
46
- getActiveAlign,
47
- getLinkAt,
48
- isCommandActive,
49
- isMarkActive,
50
- isNodeActive,
51
83
  isSafeImageUrl,
52
- isSafeLinkUrl,
53
- markRange,
54
- marksOf,
55
- nodesOf
56
- } from "./chunk-GHEFKKRC.js";
57
- import {
58
- loadPlugin,
59
- orderPlugins,
60
- resolveEntries
61
- } from "./chunk-6GWG2BLC.js";
84
+ isSafeLinkUrl
85
+ } from "./chunk-PVFKXRID.js";
62
86
 
63
- // src/i18n/en.ts
64
- var en = {
65
- "toolbar.label": "Formatting",
66
- "toolbar.options": "options",
67
- "editor.label": "Rich text editor",
68
- "editor.required": "Please fill in this field.",
69
- undo: "Undo",
70
- redo: "Redo",
71
- bold: "Bold",
72
- italic: "Italic",
73
- underline: "Underline",
74
- strike: "Strikethrough",
75
- code: "Inline code",
76
- subscript: "Subscript",
77
- superscript: "Superscript",
78
- link: "Link",
79
- unlink: "Remove link",
80
- image: "Image",
81
- bulletList: "Bulleted list",
82
- orderedList: "Numbered list",
83
- indent: "Increase indent",
84
- outdent: "Decrease indent",
85
- align: "Alignment",
86
- alignLeft: "Align left",
87
- alignCenter: "Align center",
88
- alignRight: "Align right",
89
- alignJustify: "Justify",
90
- blockquote: "Quote",
91
- codeBlock: "Code block",
92
- horizontalRule: "Horizontal line",
93
- clearFormatting: "Clear formatting",
94
- more: "More",
95
- moreFormats: "More formatting",
96
- blocks: "Text style",
97
- paragraph: "Paragraph",
98
- h1: "Heading 1",
99
- h2: "Heading 2",
100
- h3: "Heading 3",
101
- h4: "Heading 4",
102
- h5: "Heading 5",
103
- h6: "Heading 6",
104
- fontFamily: "Font",
105
- fontSize: "Font size",
106
- lineHeight: "Line height",
107
- default: "Default",
108
- textColor: "Text color",
109
- backgroundColor: "Highlight color",
110
- removeColor: "Remove color",
111
- customColor: "Custom color",
112
- "dialog.cancel": "Cancel",
113
- "dialog.save": "Save",
114
- "dialog.insert": "Insert",
115
- "dialog.close": "Close",
116
- "link.title": "Insert link",
117
- "link.editTitle": "Edit link",
118
- "link.url": "URL",
119
- "link.text": "Text to display",
120
- "link.tooltip": "Title (tooltip)",
121
- "link.newTab": "Open in new tab",
122
- "link.open": "Open link",
123
- "link.edit": "Edit link",
124
- "link.copy": "Copy link",
125
- "link.copied": "Link copied",
126
- "link.invalid": "This URL is not allowed",
127
- "image.title": "Insert image",
128
- "image.url": "Image URL",
129
- "image.alt": "Alternative text",
130
- "image.altHint": "Describe the image for people using screen readers",
131
- "image.upload": "Upload",
132
- "image.drop": "Drop an image here or click to choose",
133
- "image.uploading": "Uploading image\u2026",
134
- "image.uploadFailed": "Image upload failed",
135
- "image.invalid": "This image URL is not allowed",
136
- "image.or": "or",
137
- "image.toolbar": "Image options",
138
- "image.alignLeft": "Float left",
139
- "image.alignCenter": "Center",
140
- "image.alignRight": "Float right",
141
- "image.editAlt": "Alternative text",
142
- "image.size": "Size",
143
- "image.sizeSmall": "Small (25%)",
144
- "image.sizeMedium": "Medium (50%)",
145
- "image.sizeLarge": "Large (75%)",
146
- "image.sizeFull": "Full width",
147
- "image.sizeOriginal": "Original size",
148
- "image.delete": "Remove image",
149
- "status.words": "{count} words",
150
- pasteAsText: "Paste as text",
151
- "menu.label": "Menu",
152
- "menu.file": "File",
153
- "menu.edit": "Edit",
154
- "menu.view": "View",
155
- "menu.insert": "Insert",
156
- "menu.format": "Format",
157
- "menu.table": "Table",
158
- "menu.help": "Help",
159
- selectAll: "Select all",
160
- print: "Print",
161
- "table.rows": "Rows",
162
- "table.cols": "Columns",
163
- "table.invalidSize": "Enter a number from 1 to 50",
164
- "quickbars.selection": "Quick formatting",
165
- "quickbars.insert": "Quick insert",
166
- "search.title": "Find and replace",
167
- "search.find": "Find",
168
- "search.replace": "Replace with",
169
- "search.next": "Next match",
170
- "search.prev": "Previous match",
171
- "search.replaceOne": "Replace",
172
- "search.replaceAll": "Replace all",
173
- "search.matchCase": "Match case",
174
- "search.wholeWord": "Whole words only",
175
- "search.count": "{current} of {total}",
176
- "search.none": "No results",
177
- fullscreen: "Fullscreen",
178
- preview: "Preview",
179
- sourceCode: "Source code",
180
- help: "Keyboard shortcuts",
181
- "help.formatting": "Text formatting",
182
- "help.blocks": "Paragraphs and lists",
183
- "help.editing": "Editing",
184
- "help.navigation": "Navigation",
185
- "help.slash": "Insert block (slash commands)",
186
- "help.toMenubar": "Move to the menu bar",
187
- "help.toToolbar": "Move to the toolbar",
188
- "help.toContextToolbar": "Move to the image/table toolbar",
189
- "help.toEditor": "Back to the text",
190
- "help.nextCell": "Next table cell",
191
- table: "Table",
192
- "table.insert": "Insert table",
193
- "table.size": "{rows} \xD7 {cols}",
194
- "table.toolbar": "Table options",
195
- "table.rowBefore": "Insert row above",
196
- "table.rowAfter": "Insert row below",
197
- "table.rowDelete": "Delete row",
198
- "table.colBefore": "Insert column left",
199
- "table.colAfter": "Insert column right",
200
- "table.colDelete": "Delete column",
201
- "table.merge": "Merge cells",
202
- "table.split": "Split cell",
203
- "table.rowHeader": "Header row",
204
- "table.colHeader": "Header column",
205
- "table.cellBackground": "Cell background",
206
- "table.delete": "Delete table",
207
- "table.sort": "Sort",
208
- "table.sortAsc": "Sort A \u2192 Z, 1 \u2192 9",
209
- "table.sortDesc": "Sort Z \u2192 A, 9 \u2192 1",
210
- "table.props": "Table properties",
211
- "table.width": "Width",
212
- "table.widthHint": "For example 100% or 600px. Leave empty to fit the content.",
213
- "table.invalidWidth": "Enter a width such as 100% or 600px",
214
- "table.align": "Alignment on the page",
215
- "table.alignDefault": "Default",
216
- "table.alignCenter": "Center",
217
- "table.alignRight": "Right",
218
- "table.cellProps": "Cell properties",
219
- "table.valign": "Vertical alignment",
220
- "table.valignTop": "Top",
221
- "table.valignMiddle": "Middle",
222
- "table.valignBottom": "Bottom",
223
- "table.cellType": "Cell type",
224
- "table.cellData": "Data cell",
225
- "table.cellHeader": "Header cell",
226
- "table.colWidth": "Column width, px",
227
- "table.colWidthHint": "Leave empty to fit the content.",
228
- "table.invalidColWidth": "Enter a number from 24 to 4000",
229
- "slash.label": "Commands",
230
- "slash.empty": "No matching commands"
87
+ // src/formats.ts
88
+ import { NodeSelection } from "prosemirror-state";
89
+ import { lift, wrapIn } from "prosemirror-commands";
90
+ var INLINE_MARKS = {
91
+ strong: "bold",
92
+ b: "bold",
93
+ em: "italic",
94
+ i: "italic",
95
+ u: "underline",
96
+ s: "strike",
97
+ strike: "strike",
98
+ del: "strike",
99
+ code: "code",
100
+ sub: "subscript",
101
+ sup: "superscript"
231
102
  };
232
-
233
- // src/i18n/ru.ts
234
- var ru = {
235
- "toolbar.label": "\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",
236
- "toolbar.options": "\u0432\u0430\u0440\u0438\u0430\u043D\u0442\u044B",
237
- "editor.label": "\u0422\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440",
238
- "editor.required": "\u0417\u0430\u043F\u043E\u043B\u043D\u0438\u0442\u0435 \u044D\u0442\u043E \u043F\u043E\u043B\u0435.",
239
- undo: "\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C",
240
- redo: "\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C",
241
- bold: "\u0416\u0438\u0440\u043D\u044B\u0439",
242
- italic: "\u041A\u0443\u0440\u0441\u0438\u0432",
243
- underline: "\u041F\u043E\u0434\u0447\u0451\u0440\u043A\u043D\u0443\u0442\u044B\u0439",
244
- strike: "\u0417\u0430\u0447\u0451\u0440\u043A\u043D\u0443\u0442\u044B\u0439",
245
- code: "\u041A\u043E\u0434 \u0432 \u0441\u0442\u0440\u043E\u043A\u0435",
246
- subscript: "\u041F\u043E\u0434\u0441\u0442\u0440\u043E\u0447\u043D\u044B\u0439",
247
- superscript: "\u041D\u0430\u0434\u0441\u0442\u0440\u043E\u0447\u043D\u044B\u0439",
248
- link: "\u0421\u0441\u044B\u043B\u043A\u0430",
249
- unlink: "\u0423\u0431\u0440\u0430\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0443",
250
- image: "\u0418\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435",
251
- bulletList: "\u041C\u0430\u0440\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A",
252
- orderedList: "\u041D\u0443\u043C\u0435\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A",
253
- indent: "\u0423\u0432\u0435\u043B\u0438\u0447\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F",
254
- outdent: "\u0423\u043C\u0435\u043D\u044C\u0448\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F",
255
- align: "\u0412\u044B\u0440\u0430\u0432\u043D\u0438\u0432\u0430\u043D\u0438\u0435",
256
- alignLeft: "\u041F\u043E \u043B\u0435\u0432\u043E\u043C\u0443 \u043A\u0440\u0430\u044E",
257
- alignCenter: "\u041F\u043E \u0446\u0435\u043D\u0442\u0440\u0443",
258
- alignRight: "\u041F\u043E \u043F\u0440\u0430\u0432\u043E\u043C\u0443 \u043A\u0440\u0430\u044E",
259
- alignJustify: "\u041F\u043E \u0448\u0438\u0440\u0438\u043D\u0435",
260
- blockquote: "\u0426\u0438\u0442\u0430\u0442\u0430",
261
- codeBlock: "\u0411\u043B\u043E\u043A \u043A\u043E\u0434\u0430",
262
- horizontalRule: "\u0413\u043E\u0440\u0438\u0437\u043E\u043D\u0442\u0430\u043B\u044C\u043D\u0430\u044F \u043B\u0438\u043D\u0438\u044F",
263
- clearFormatting: "\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",
264
- more: "\u0415\u0449\u0451",
265
- moreFormats: "\u0415\u0449\u0451 \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",
266
- blocks: "\u0421\u0442\u0438\u043B\u044C \u0442\u0435\u043A\u0441\u0442\u0430",
267
- paragraph: "\u041E\u0431\u044B\u0447\u043D\u044B\u0439 \u0442\u0435\u043A\u0441\u0442",
268
- h1: "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A 1",
269
- h2: "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A 2",
270
- h3: "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A 3",
271
- h4: "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A 4",
272
- h5: "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A 5",
273
- h6: "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A 6",
274
- fontFamily: "\u0428\u0440\u0438\u0444\u0442",
275
- fontSize: "\u0420\u0430\u0437\u043C\u0435\u0440 \u0448\u0440\u0438\u0444\u0442\u0430",
276
- lineHeight: "\u041C\u0435\u0436\u0441\u0442\u0440\u043E\u0447\u043D\u044B\u0439 \u0438\u043D\u0442\u0435\u0440\u0432\u0430\u043B",
277
- default: "\u041F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E",
278
- textColor: "\u0426\u0432\u0435\u0442 \u0442\u0435\u043A\u0441\u0442\u0430",
279
- backgroundColor: "\u0426\u0432\u0435\u0442 \u0432\u044B\u0434\u0435\u043B\u0435\u043D\u0438\u044F",
280
- removeColor: "\u0423\u0431\u0440\u0430\u0442\u044C \u0446\u0432\u0435\u0442",
281
- customColor: "\u0421\u0432\u043E\u0439 \u0446\u0432\u0435\u0442",
282
- "dialog.cancel": "\u041E\u0442\u043C\u0435\u043D\u0430",
283
- "dialog.save": "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C",
284
- "dialog.insert": "\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u044C",
285
- "dialog.close": "\u0417\u0430\u043A\u0440\u044B\u0442\u044C",
286
- "link.title": "\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0443",
287
- "link.editTitle": "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0443",
288
- "link.url": "\u0410\u0434\u0440\u0435\u0441",
289
- "link.text": "\u0422\u0435\u043A\u0441\u0442 \u0441\u0441\u044B\u043B\u043A\u0438",
290
- "link.tooltip": "\u041F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0430 (title)",
291
- "link.newTab": "\u041E\u0442\u043A\u0440\u044B\u0432\u0430\u0442\u044C \u0432 \u043D\u043E\u0432\u043E\u0439 \u0432\u043A\u043B\u0430\u0434\u043A\u0435",
292
- "link.open": "\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0443",
293
- "link.edit": "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0443",
294
- "link.copy": "\u041A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0443",
295
- "link.copied": "\u0421\u0441\u044B\u043B\u043A\u0430 \u0441\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u043D\u0430",
296
- "link.invalid": "\u0422\u0430\u043A\u043E\u0439 \u0430\u0434\u0440\u0435\u0441 \u043D\u0435 \u0440\u0430\u0437\u0440\u0435\u0448\u0451\u043D",
297
- "image.title": "\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435",
298
- "image.url": "\u0410\u0434\u0440\u0435\u0441 \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F",
299
- "image.alt": "\u0410\u043B\u044C\u0442\u0435\u0440\u043D\u0430\u0442\u0438\u0432\u043D\u044B\u0439 \u0442\u0435\u043A\u0441\u0442",
300
- "image.altHint": "\u041E\u043F\u0438\u0448\u0438\u0442\u0435 \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435 \u0434\u043B\u044F \u043B\u044E\u0434\u0435\u0439, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u044E\u0449\u0438\u0445 \u044D\u043A\u0440\u0430\u043D\u043D\u044B\u0439 \u0434\u0438\u043A\u0442\u043E\u0440",
301
- "image.upload": "\u0417\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C",
302
- "image.drop": "\u041F\u0435\u0440\u0435\u0442\u0430\u0449\u0438\u0442\u0435 \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435 \u0441\u044E\u0434\u0430 \u0438\u043B\u0438 \u043D\u0430\u0436\u043C\u0438\u0442\u0435, \u0447\u0442\u043E\u0431\u044B \u0432\u044B\u0431\u0440\u0430\u0442\u044C",
303
- "image.uploading": "\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430 \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u2026",
304
- "image.uploadFailed": "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435",
305
- "image.invalid": "\u0422\u0430\u043A\u043E\u0439 \u0430\u0434\u0440\u0435\u0441 \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F \u043D\u0435 \u0440\u0430\u0437\u0440\u0435\u0448\u0451\u043D",
306
- "image.or": "\u0438\u043B\u0438",
307
- "image.toolbar": "\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F",
308
- "image.alignLeft": "\u041E\u0431\u0442\u0435\u043A\u0430\u043D\u0438\u0435, \u0441\u043B\u0435\u0432\u0430",
309
- "image.alignCenter": "\u041F\u043E \u0446\u0435\u043D\u0442\u0440\u0443",
310
- "image.alignRight": "\u041E\u0431\u0442\u0435\u043A\u0430\u043D\u0438\u0435, \u0441\u043F\u0440\u0430\u0432\u0430",
311
- "image.editAlt": "\u0410\u043B\u044C\u0442\u0435\u0440\u043D\u0430\u0442\u0438\u0432\u043D\u044B\u0439 \u0442\u0435\u043A\u0441\u0442",
312
- "image.size": "\u0420\u0430\u0437\u043C\u0435\u0440",
313
- "image.sizeSmall": "\u041C\u0430\u043B\u0435\u043D\u044C\u043A\u0438\u0439 (25%)",
314
- "image.sizeMedium": "\u0421\u0440\u0435\u0434\u043D\u0438\u0439 (50%)",
315
- "image.sizeLarge": "\u0411\u043E\u043B\u044C\u0448\u043E\u0439 (75%)",
316
- "image.sizeFull": "\u0412\u043E \u0432\u0441\u044E \u0448\u0438\u0440\u0438\u043D\u0443",
317
- "image.sizeOriginal": "\u0418\u0441\u0445\u043E\u0434\u043D\u044B\u0439 \u0440\u0430\u0437\u043C\u0435\u0440",
318
- "image.delete": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435",
319
- "status.words": "\u0421\u043B\u043E\u0432: {count}",
320
- pasteAsText: "\u0412\u0441\u0442\u0430\u0432\u043B\u044F\u0442\u044C \u043A\u0430\u043A \u0442\u0435\u043A\u0441\u0442",
321
- "menu.label": "\u041C\u0435\u043D\u044E",
322
- "menu.file": "\u0424\u0430\u0439\u043B",
323
- "menu.edit": "\u041F\u0440\u0430\u0432\u043A\u0430",
324
- "menu.view": "\u0412\u0438\u0434",
325
- "menu.insert": "\u0412\u0441\u0442\u0430\u0432\u043A\u0430",
326
- "menu.format": "\u0424\u043E\u0440\u043C\u0430\u0442",
327
- "menu.table": "\u0422\u0430\u0431\u043B\u0438\u0446\u0430",
328
- "menu.help": "\u0421\u043F\u0440\u0430\u0432\u043A\u0430",
329
- selectAll: "\u0412\u044B\u0434\u0435\u043B\u0438\u0442\u044C \u0432\u0441\u0451",
330
- print: "\u041F\u0435\u0447\u0430\u0442\u044C",
331
- "table.rows": "\u0421\u0442\u0440\u043E\u043A\u0438",
332
- "table.cols": "\u0421\u0442\u043E\u043B\u0431\u0446\u044B",
333
- "table.invalidSize": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043B\u043E \u043E\u0442 1 \u0434\u043E 50",
334
- "quickbars.selection": "\u0411\u044B\u0441\u0442\u0440\u043E\u0435 \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",
335
- "quickbars.insert": "\u0411\u044B\u0441\u0442\u0440\u0430\u044F \u0432\u0441\u0442\u0430\u0432\u043A\u0430",
336
- "search.title": "\u041D\u0430\u0439\u0442\u0438 \u0438 \u0437\u0430\u043C\u0435\u043D\u0438\u0442\u044C",
337
- "search.find": "\u041D\u0430\u0439\u0442\u0438",
338
- "search.replace": "\u0417\u0430\u043C\u0435\u043D\u0438\u0442\u044C \u043D\u0430",
339
- "search.next": "\u0421\u043B\u0435\u0434\u0443\u044E\u0449\u0435\u0435 \u0441\u043E\u0432\u043F\u0430\u0434\u0435\u043D\u0438\u0435",
340
- "search.prev": "\u041F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0435 \u0441\u043E\u0432\u043F\u0430\u0434\u0435\u043D\u0438\u0435",
341
- "search.replaceOne": "\u0417\u0430\u043C\u0435\u043D\u0438\u0442\u044C",
342
- "search.replaceAll": "\u0417\u0430\u043C\u0435\u043D\u0438\u0442\u044C \u0432\u0441\u0435",
343
- "search.matchCase": "\u0423\u0447\u0438\u0442\u044B\u0432\u0430\u0442\u044C \u0440\u0435\u0433\u0438\u0441\u0442\u0440",
344
- "search.wholeWord": "\u0422\u043E\u043B\u044C\u043A\u043E \u0441\u043B\u043E\u0432\u043E \u0446\u0435\u043B\u0438\u043A\u043E\u043C",
345
- "search.count": "{current} \u0438\u0437 {total}",
346
- "search.none": "\u041D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E",
347
- fullscreen: "\u041D\u0430 \u0432\u0435\u0441\u044C \u044D\u043A\u0440\u0430\u043D",
348
- preview: "\u041F\u0440\u0435\u0434\u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440",
349
- sourceCode: "HTML-\u043A\u043E\u0434",
350
- help: "\u0413\u043E\u0440\u044F\u0447\u0438\u0435 \u043A\u043B\u0430\u0432\u0438\u0448\u0438",
351
- "help.formatting": "\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 \u0442\u0435\u043A\u0441\u0442\u0430",
352
- "help.blocks": "\u0410\u0431\u0437\u0430\u0446\u044B \u0438 \u0441\u043F\u0438\u0441\u043A\u0438",
353
- "help.editing": "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",
354
- "help.navigation": "\u041D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F",
355
- "help.slash": "\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0431\u043B\u043E\u043A (\u0441\u043B\u044D\u0448-\u043A\u043E\u043C\u0430\u043D\u0434\u044B)",
356
- "help.toMenubar": "\u041F\u0435\u0440\u0435\u0439\u0442\u0438 \u0432 \u0433\u043B\u0430\u0432\u043D\u043E\u0435 \u043C\u0435\u043D\u044E",
357
- "help.toToolbar": "\u041F\u0435\u0440\u0435\u0439\u0442\u0438 \u043D\u0430 \u043F\u0430\u043D\u0435\u043B\u044C \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432",
358
- "help.toContextToolbar": "\u041F\u0435\u0440\u0435\u0439\u0442\u0438 \u043D\u0430 \u043F\u0430\u043D\u0435\u043B\u044C \u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438/\u0442\u0430\u0431\u043B\u0438\u0446\u044B",
359
- "help.toEditor": "\u0412\u0435\u0440\u043D\u0443\u0442\u044C\u0441\u044F \u0432 \u0442\u0435\u043A\u0441\u0442",
360
- "help.nextCell": "\u0421\u043B\u0435\u0434\u0443\u044E\u0449\u0430\u044F \u044F\u0447\u0435\u0439\u043A\u0430 \u0442\u0430\u0431\u043B\u0438\u0446\u044B",
361
- table: "\u0422\u0430\u0431\u043B\u0438\u0446\u0430",
362
- "table.insert": "\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0442\u0430\u0431\u043B\u0438\u0446\u0443",
363
- "table.size": "{rows} \xD7 {cols}",
364
- "table.toolbar": "\u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0442\u0430\u0431\u043B\u0438\u0446\u044B",
365
- "table.rowBefore": "\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0441\u0442\u0440\u043E\u043A\u0443 \u0432\u044B\u0448\u0435",
366
- "table.rowAfter": "\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0441\u0442\u0440\u043E\u043A\u0443 \u043D\u0438\u0436\u0435",
367
- "table.rowDelete": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0442\u0440\u043E\u043A\u0443",
368
- "table.colBefore": "\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0441\u0442\u043E\u043B\u0431\u0435\u0446 \u0441\u043B\u0435\u0432\u0430",
369
- "table.colAfter": "\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0441\u0442\u043E\u043B\u0431\u0435\u0446 \u0441\u043F\u0440\u0430\u0432\u0430",
370
- "table.colDelete": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0442\u043E\u043B\u0431\u0435\u0446",
371
- "table.merge": "\u041E\u0431\u044A\u0435\u0434\u0438\u043D\u0438\u0442\u044C \u044F\u0447\u0435\u0439\u043A\u0438",
372
- "table.split": "\u0420\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u044C \u044F\u0447\u0435\u0439\u043A\u0443",
373
- "table.rowHeader": "\u0421\u0442\u0440\u043E\u043A\u0430 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432",
374
- "table.colHeader": "\u0421\u0442\u043E\u043B\u0431\u0435\u0446 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432",
375
- "table.cellBackground": "\u0424\u043E\u043D \u044F\u0447\u0435\u0439\u043A\u0438",
376
- "table.delete": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0442\u0430\u0431\u043B\u0438\u0446\u0443",
377
- "table.sort": "\u0421\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u043A\u0430",
378
- "table.sortAsc": "\u0421\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0410 \u2192 \u042F, 1 \u2192 9",
379
- "table.sortDesc": "\u0421\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u042F \u2192 \u0410, 9 \u2192 1",
380
- "table.props": "\u0421\u0432\u043E\u0439\u0441\u0442\u0432\u0430 \u0442\u0430\u0431\u043B\u0438\u0446\u044B",
381
- "table.width": "\u0428\u0438\u0440\u0438\u043D\u0430",
382
- "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.",
383
- "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",
384
- "table.align": "\u0412\u044B\u0440\u0430\u0432\u043D\u0438\u0432\u0430\u043D\u0438\u0435 \u043D\u0430 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0435",
385
- "table.alignDefault": "\u041F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E",
386
- "table.alignCenter": "\u041F\u043E \u0446\u0435\u043D\u0442\u0440\u0443",
387
- "table.alignRight": "\u0421\u043F\u0440\u0430\u0432\u0430",
388
- "table.cellProps": "\u0421\u0432\u043E\u0439\u0441\u0442\u0432\u0430 \u044F\u0447\u0435\u0439\u043A\u0438",
389
- "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",
390
- "table.valignTop": "\u0421\u0432\u0435\u0440\u0445\u0443",
391
- "table.valignMiddle": "\u041F\u043E \u0446\u0435\u043D\u0442\u0440\u0443",
392
- "table.valignBottom": "\u0421\u043D\u0438\u0437\u0443",
393
- "table.cellType": "\u0422\u0438\u043F \u044F\u0447\u0435\u0439\u043A\u0438",
394
- "table.cellData": "\u041E\u0431\u044B\u0447\u043D\u0430\u044F",
395
- "table.cellHeader": "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A",
396
- "table.colWidth": "\u0428\u0438\u0440\u0438\u043D\u0430 \u0441\u0442\u043E\u043B\u0431\u0446\u0430, px",
397
- "table.colWidthHint": "\u041F\u0443\u0441\u0442\u043E \u2014 \u043F\u043E \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u043C\u0443.",
398
- "table.invalidColWidth": "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0447\u0438\u0441\u043B\u043E \u043E\u0442 24 \u0434\u043E 4000",
399
- "slash.label": "\u041A\u043E\u043C\u0430\u043D\u0434\u044B",
400
- "slash.empty": "\u041D\u0435\u0442 \u043F\u043E\u0434\u0445\u043E\u0434\u044F\u0449\u0438\u0445 \u043A\u043E\u043C\u0430\u043D\u0434"
103
+ var INLINE_STYLES = {
104
+ color: { mark: "color", read: cssValue.color },
105
+ "background-color": { mark: "background", read: cssValue.color },
106
+ "font-family": { mark: "font_family", read: cssValue.fontFamily },
107
+ "font-size": { mark: "font_size", read: cssValue.length }
401
108
  };
402
-
403
- // src/i18n/index.ts
404
- var builtin = { en, ru };
405
- function registerLanguage(code, messages) {
406
- builtin[code.toLowerCase()] = { ...en, ...messages };
109
+ var BLOCK_TAGS = {
110
+ p: (n) => n.type.name === "paragraph",
111
+ h1: (n) => n.type.name === "heading" && n.attrs.level === 1,
112
+ h2: (n) => n.type.name === "heading" && n.attrs.level === 2,
113
+ h3: (n) => n.type.name === "heading" && n.attrs.level === 3,
114
+ h4: (n) => n.type.name === "heading" && n.attrs.level === 4,
115
+ h5: (n) => n.type.name === "heading" && n.attrs.level === 5,
116
+ h6: (n) => n.type.name === "heading" && n.attrs.level === 6,
117
+ blockquote: (n) => n.type.name === "blockquote",
118
+ pre: (n) => n.type.name === "code_block",
119
+ img: (n) => n.type.name === "image"
120
+ };
121
+ var warned = /* @__PURE__ */ new Set();
122
+ function warnOnce(message) {
123
+ if (warned.has(message)) return;
124
+ warned.add(message);
125
+ console.warn(`[nova] formats: ${message}`);
407
126
  }
408
- function createTranslator(language = "en", overrides = {}) {
409
- const code = language.toLowerCase();
410
- const pack = builtin[code] ?? builtin[code.split("-")[0]] ?? en;
411
- const messages = { ...en, ...pack, ...overrides };
412
- return (key3, params) => {
413
- const template = messages[key3] ?? key3;
414
- if (!params) return template;
415
- return template.replace(/\{(\w+)\}/g, (_, name) => String(params[name] ?? `{${name}}`));
416
- };
127
+ function classList(value) {
128
+ if (Array.isArray(value)) return value.flatMap(classList);
129
+ return typeof value === "string" ? value.split(/\s+/).filter(Boolean) : [];
417
130
  }
418
-
419
- // src/paste.ts
420
- import { Slice } from "prosemirror-model";
421
- import { Plugin, PluginKey } from "prosemirror-state";
422
-
423
- // src/paste-office.ts
424
- function detectPasteSource(html) {
425
- if (/data-pm-slice=/.test(html)) return "nova";
426
- if (/<google-sheets-html-origin|data-sheets-(root|value)/i.test(html)) return "google-sheets";
427
- if (/id="docs-internal-guid-/.test(html)) return "google-docs";
428
- if (/urn:schemas-microsoft-com:office:excel|ProgId"?\s+content="?Excel\.Sheet/i.test(html))
429
- return "excel";
430
- if (/urn:schemas-microsoft-com:office:word|class="?Mso|mso-list:|content="?Microsoft Word/i.test(
431
- html
432
- ))
433
- return "word";
434
- if (/class="[^"]*\b(TextRun|OutlineElement|EOP|SCXW\d+|BCX\d+)\b|data-ccp-props|paraid=/.test(html))
435
- return "word-online";
436
- if (/content="?LibreOffice|content="?OpenOffice/i.test(html)) return "libreoffice";
437
- return "web";
131
+ function formatClasses(specs) {
132
+ const out = [];
133
+ for (const spec of specs) {
134
+ out.push(...classList(spec.classes));
135
+ if ("items" in spec && spec.items) out.push(...formatClasses(spec.items));
136
+ }
137
+ return out;
438
138
  }
439
- function cleanPastedHTML(html, styles = "clean") {
440
- const source = detectPasteSource(html);
441
- if (source === "nova") return html;
442
- const template = document.createElement("template");
443
- template.innerHTML = html;
444
- const root = document.createElement("div");
445
- root.append(template.content);
446
- inlineClassStyles(root);
447
- removeJunk(root);
448
- if (source === "word") convertWordLists(root);
449
- if (source === "google-docs") unwrapGoogleDocsWrapper(root);
450
- normalizeLists(root);
451
- convertWordParagraphStyles(root);
452
- root.querySelectorAll("[style]").forEach((el) => cleanStyle(el, styles));
453
- if (styles === "clean") stripLayoutAttributes(root);
454
- unwrapMeaningless(root);
455
- removeBreaksBetweenBlocks(root);
456
- normalizeEmptyParagraphs(root);
457
- wrapCellContent(root);
458
- return root.innerHTML;
139
+ var hasClasses = (value, wanted) => {
140
+ const have = classList(value);
141
+ return wanted.every((c) => have.includes(c));
142
+ };
143
+ var withClasses = (value, add) => {
144
+ const merged = [.../* @__PURE__ */ new Set([...classList(value), ...add])];
145
+ return merged.length ? merged.join(" ") : null;
146
+ };
147
+ var withoutClasses = (value, drop) => {
148
+ const rest = classList(value).filter((c) => !drop.includes(c));
149
+ return rest.length ? rest.join(" ") : null;
150
+ };
151
+ function blockStyles(spec) {
152
+ const out = {};
153
+ for (const [prop, value] of Object.entries(spec.styles ?? {})) {
154
+ if (prop === "text-align" && ALIGNMENTS.includes(value))
155
+ out.align = value;
156
+ else if (prop === "line-height" && cssValue.lineHeight(value))
157
+ out.lineHeight = cssValue.lineHeight(value);
158
+ else warnOnce(`style "${prop}" is not supported on blocks`);
159
+ }
160
+ return out;
459
161
  }
460
- function parseDeclarations(css) {
461
- const out = /* @__PURE__ */ new Map();
462
- for (const part of css.split(";")) {
463
- const colon = part.indexOf(":");
464
- if (colon < 0) continue;
465
- const name = part.slice(0, colon).trim().toLowerCase();
466
- const value = part.slice(colon + 1).trim().replace(/\s*!important$/i, "");
467
- if (name && value) out.set(name, value);
162
+ function inlineMarks(state, spec) {
163
+ const marks = marksOf(state);
164
+ const out = [];
165
+ if (spec.inline && spec.inline !== "span") {
166
+ const type = marks[INLINE_MARKS[spec.inline]];
167
+ if (type) out.push(type.create());
168
+ }
169
+ const classes = classList(spec.classes);
170
+ if (classes.length && marks.span_class)
171
+ out.push(marks.span_class.create({ class: classes.join(" ") }));
172
+ for (const [prop, raw] of Object.entries(spec.styles ?? {})) {
173
+ const style = INLINE_STYLES[prop];
174
+ const value = style?.read(raw);
175
+ const type = style ? marks[style.mark] : void 0;
176
+ if (type && value) out.push(type.create({ value }));
177
+ else warnOnce(`style "${prop}: ${raw}" is not supported on text`);
468
178
  }
469
179
  return out;
470
180
  }
471
- function serializeDeclarations(decls) {
472
- return [...decls].map(([name, value]) => `${name}: ${value}`).join("; ");
181
+ var selectorTags = (spec) => (spec.selector ?? "").split(",").map((s) => s.trim().toLowerCase()).filter((tag) => {
182
+ if (BLOCK_TAGS[tag]) return true;
183
+ warnOnce(`selector "${tag}" is not supported`);
184
+ return false;
185
+ });
186
+ function selectedNodes(state, tags) {
187
+ const out = [];
188
+ const matches = (node) => tags.some((tag) => BLOCK_TAGS[tag](node));
189
+ const { selection } = state;
190
+ if (selection instanceof NodeSelection && matches(selection.node)) {
191
+ return [{ node: selection.node, pos: selection.from }];
192
+ }
193
+ const { $from, from, to } = selection;
194
+ for (let depth = $from.depth; depth > 0; depth--) {
195
+ const node = $from.node(depth);
196
+ if (matches(node)) out.push({ node, pos: $from.before(depth) });
197
+ }
198
+ state.doc.nodesBetween(from, to, (node, pos) => {
199
+ if (matches(node) && !out.some((o) => o.pos === pos)) out.push({ node, pos });
200
+ });
201
+ return out;
473
202
  }
474
- function inlineClassStyles(root) {
475
- const sheets = [...root.querySelectorAll("style")].map((s) => s.textContent ?? "");
476
- if (!sheets.length) return;
477
- const rules = [];
478
- const css = sheets.join("\n").replace(/\/\*[\s\S]*?\*\//g, "").replace(/<!--|-->/g, "");
479
- for (const match of css.matchAll(/([^{}@]+)\{([^{}]*)\}/g)) {
480
- const decls = parseDeclarations(match[2]);
481
- for (const selector of match[1].split(",")) {
482
- const m = selector.trim().match(/^([a-z][a-z0-9]*)?\.([\w-]+)$/i);
483
- if (m) rules.push({ tag: (m[1] ?? "").toLowerCase(), cls: m[2], decls });
484
- }
485
- }
486
- if (!rules.length) return;
487
- root.querySelectorAll("[class]").forEach((el) => {
488
- const classes = el.className.split(/\s+/).filter(Boolean);
489
- const merged = /* @__PURE__ */ new Map();
490
- for (const rule of rules) {
491
- if (!classes.includes(rule.cls)) continue;
492
- if (rule.tag && rule.tag !== el.tagName.toLowerCase()) continue;
493
- rule.decls.forEach((value, name) => merged.set(name, value));
203
+ function textBlocks(state) {
204
+ const out = [];
205
+ const { from, to } = state.selection;
206
+ state.doc.nodesBetween(from, to, (node, pos) => {
207
+ if (node.isTextblock) {
208
+ out.push({ node, pos });
209
+ return false;
494
210
  }
495
- if (!merged.size) return;
496
- parseDeclarations(el.getAttribute("style") ?? "").forEach(
497
- (value, name) => merged.set(name, value)
498
- );
499
- el.setAttribute("style", serializeDeclarations(merged));
211
+ return true;
500
212
  });
213
+ return out;
501
214
  }
502
- var DROP_TAGS = /^(STYLE|SCRIPT|META|LINK|TITLE|XML|HEAD|NOSCRIPT|TEMPLATE)$/;
503
- function removeJunk(root) {
504
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
505
- const comments = [];
506
- while (walker.nextNode()) comments.push(walker.currentNode);
507
- comments.forEach((c) => c.parentNode?.removeChild(c));
508
- for (const el of [...root.querySelectorAll("*")]) {
509
- if (!root.contains(el)) continue;
510
- const tag = el.tagName.toUpperCase();
511
- if (DROP_TAGS.test(tag)) {
512
- el.remove();
513
- continue;
514
- }
515
- if (tag.includes(":")) {
516
- const prefix = tag.split(":")[0];
517
- if (prefix === "O" || prefix === "V") el.remove();
518
- else unwrap(el);
519
- }
215
+ function blockquoteAt(state) {
216
+ const { $from } = state.selection;
217
+ for (let depth = $from.depth; depth > 0; depth--) {
218
+ const node = $from.node(depth);
219
+ if (node.type.name === "blockquote") return { node, pos: $from.before(depth) };
520
220
  }
521
- root.querySelectorAll("span.EOP").forEach((span) => {
522
- if (/^\s*$/.test(span.textContent ?? "")) span.remove();
523
- });
524
- root.querySelectorAll("a").forEach((a) => {
525
- const href = a.getAttribute("href") ?? "";
526
- const redirect = href.match(/^https?:\/\/(www\.)?google\.[a-z.]+\/url\?(.*)$/i);
527
- if (redirect) {
528
- const target = new URLSearchParams(redirect[2]).get("q");
529
- if (target) a.setAttribute("href", target);
530
- }
531
- if (!href || /^#_(ftn|edn|msocom|Toc|Ref)/i.test(href)) unwrap(a);
532
- });
533
- root.querySelectorAll('br[style*="page-break"]').forEach((br) => br.remove());
534
- root.querySelectorAll(
535
- '[style*="mso-element:footnote-list"], [style*="mso-element:comment-list"], [style*="mso-element:endnote-list"]'
536
- ).forEach((el) => el.remove());
221
+ return null;
537
222
  }
538
- var ORDERED_MARKER = /^[([]?(\d+(\.\d+)*[.)\]]?|[a-z]{1,4}[.)\]])$/i;
539
- function readWordListItem(el) {
540
- const css = el.getAttribute("style") ?? "";
541
- const match = css.match(/mso-list:\s*(l\d+)\s+level(\d+)/i);
542
- if (!match) return null;
543
- const markerEl = [...el.querySelectorAll("[style]")].find(
544
- (s) => /mso-list:\s*Ignore/i.test(s.getAttribute("style") ?? "")
545
- );
546
- const marker = (markerEl?.textContent ?? "").replace(/\s+/g, "");
547
- markerEl?.remove();
548
- const ordered = ORDERED_MARKER.test(marker);
549
- const { style, start } = ordered ? numbering(marker) : { style: bulletStyle(marker), start: 1 };
223
+ function keepBlockStyle(attrs) {
550
224
  return {
551
- el,
552
- level: Math.max(1, Math.min(9, Number(match[2]))),
553
- ordered,
554
- start,
555
- style
225
+ align: attrs.align ?? null,
226
+ lineHeight: attrs.lineHeight ?? null,
227
+ dir: attrs.dir ?? null
556
228
  };
557
229
  }
558
- var ROMAN = /^(i|ii|iii|iv|v|vi|vii|viii|ix|x|xi|xii)$/i;
559
- var ROMAN_VALUES = { i: 1, v: 5, x: 10 };
560
- function romanToNumber(roman) {
561
- let total = 0;
562
- const chars = roman.toLowerCase();
563
- for (let i = 0; i < chars.length; i++) {
564
- const value = ROMAN_VALUES[chars[i]];
565
- const next = ROMAN_VALUES[chars[i + 1] ?? ""] ?? 0;
566
- total += value < next ? -value : value;
567
- }
568
- return total;
569
- }
570
- function numbering(marker) {
571
- const digits = marker.match(/\d+/);
572
- if (digits) return { style: null, start: Number(digits[0]) };
573
- const letters = marker.replace(/[^a-z]/gi, "");
574
- if (ROMAN.test(letters)) {
575
- return {
576
- style: letters === letters.toLowerCase() ? "lower-roman" : "upper-roman",
577
- start: romanToNumber(letters)
578
- };
230
+ var Formatter = class {
231
+ constructor(editor, allowedClasses) {
232
+ this.editor = editor;
233
+ this.allowedClasses = allowedClasses;
579
234
  }
580
- const lower = letters === letters.toLowerCase();
581
- return {
582
- style: lower ? "lower-alpha" : "upper-alpha",
583
- start: letters.toLowerCase().charCodeAt(0) - 96
584
- };
235
+ editor;
236
+ allowedClasses;
237
+ registry = /* @__PURE__ */ new Map();
238
+ /** Зарегистрировать именованный формат (одно описание или несколько вариантов). */
239
+ register(name, spec) {
240
+ const specs = Array.isArray(spec) ? spec : [spec];
241
+ this.registry.set(name, specs);
242
+ formatClasses(specs).forEach((c) => this.allowedClasses.add(c));
243
+ }
244
+ unregister(name) {
245
+ this.registry.delete(name);
246
+ }
247
+ has(name) {
248
+ return this.registry.has(name);
249
+ }
250
+ get(name) {
251
+ return this.registry.get(name);
252
+ }
253
+ resolve(format) {
254
+ if (typeof format !== "string") return [format];
255
+ const specs = this.registry.get(format);
256
+ if (!specs) warnOnce(`unknown format "${format}"`);
257
+ return specs ?? [];
258
+ }
259
+ /** Можно ли применить формат к выделению (для selector — есть ли подходящие элементы). */
260
+ canApply(format) {
261
+ if (!this.editor.isEditable()) return false;
262
+ const state = this.editor.view.state;
263
+ return this.resolve(format).some((spec) => canApply(state, spec));
264
+ }
265
+ /** Подходит ли выделение под формат. */
266
+ match(format) {
267
+ const state = this.editor.view.state;
268
+ return this.resolve(format).some((spec) => matchSpec(state, spec));
269
+ }
270
+ apply(format) {
271
+ if (!this.editor.isEditable()) return false;
272
+ const specs = this.resolve(format);
273
+ if (!specs.length) return false;
274
+ const spec = specs.find((s) => canApply(this.editor.view.state, s)) ?? specs[0];
275
+ return this.run((state, tr) => applySpec(state, tr, spec));
276
+ }
277
+ remove(format) {
278
+ if (!this.editor.isEditable()) return false;
279
+ const specs = this.resolve(format);
280
+ if (!specs.length) return false;
281
+ return this.run((state, tr) => specs.forEach((spec) => removeSpec(state, tr, spec)));
282
+ }
283
+ toggle(format) {
284
+ return this.match(format) ? this.remove(format) : this.apply(format);
285
+ }
286
+ run(fn) {
287
+ const { view } = this.editor;
288
+ const tr = view.state.tr;
289
+ const result = fn(view.state, tr);
290
+ if (result === false) return false;
291
+ if (tr.docChanged || tr.storedMarksSet) view.dispatch(tr.scrollIntoView());
292
+ view.focus();
293
+ return true;
294
+ }
295
+ };
296
+ function canApply(state, spec) {
297
+ if (spec.selector) return selectedNodes(state, selectorTags(spec)).length > 0;
298
+ return true;
585
299
  }
586
- function bulletStyle(marker) {
587
- if (marker === "o") return "circle";
588
- if (/^[§▪■]$/.test(marker)) return "square";
589
- return null;
300
+ function hasBlockStyles(node, spec) {
301
+ if (node.type.name === "image") return true;
302
+ return Object.entries(blockStyles(spec)).every(([key3, value]) => node.attrs[key3] === value);
590
303
  }
591
- function convertWordLists(root) {
592
- const candidates = [
593
- ...root.querySelectorAll("p, div, h1, h2, h3, h4, h5, h6")
594
- ].filter((el) => /mso-list:\s*l\d+\s+level\d+/i.test(el.getAttribute("style") ?? ""));
595
- for (const heading of candidates.filter((el) => /^H[1-6]$/.test(el.tagName))) {
596
- heading.querySelectorAll("[style]").forEach((s) => {
597
- if (!/mso-list:\s*Ignore/i.test(s.getAttribute("style") ?? "")) return;
598
- const marker = (s.textContent ?? "").replace(/\s+/g, "");
599
- s.replaceWith(s.ownerDocument.createTextNode(`${marker} `));
600
- });
304
+ function matchSpec(state, spec) {
305
+ const classes = classList(spec.classes);
306
+ if (spec.block) {
307
+ if (spec.block === "blockquote") {
308
+ const quote = blockquoteAt(state);
309
+ return !!quote && hasClasses(quote.node.attrs.class, classes);
310
+ }
311
+ const node = state.selection.$from.parent;
312
+ return BLOCK_TAGS[spec.block](node) && hasClasses(node.attrs.class, classes) && hasBlockStyles(node, spec);
313
+ }
314
+ if (spec.selector) {
315
+ const nodes = selectedNodes(state, selectorTags(spec));
316
+ return nodes.length > 0 && nodes.some(({ node }) => hasClasses(node.attrs.class, classes) && hasBlockStyles(node, spec));
601
317
  }
602
- const paragraphs = candidates.filter((el) => !/^H[1-6]$/.test(el.tagName));
603
- const done = /* @__PURE__ */ new Set();
604
- for (const first of paragraphs) {
605
- if (done.has(first)) continue;
606
- const run = [];
607
- let node = first;
608
- while (node instanceof HTMLElement && paragraphs.includes(node)) {
609
- const item = readWordListItem(node);
610
- if (!item) break;
611
- run.push(item);
612
- done.add(node);
613
- node = nextElement(node);
318
+ if (spec.inline) {
319
+ const wanted = inlineMarks(state, spec);
320
+ if (!wanted.length) return false;
321
+ const { $from, empty, from, to } = state.selection;
322
+ if (empty) {
323
+ const marks = state.storedMarks ?? $from.marks();
324
+ return wanted.every((mark) => marks.some((m) => markCovers(m, mark)));
614
325
  }
615
- if (run.length) buildNestedList(run);
326
+ let found = false;
327
+ let all = true;
328
+ state.doc.nodesBetween(from, to, (node) => {
329
+ if (!node.isText) return;
330
+ found = true;
331
+ if (!wanted.every((mark) => node.marks.some((m) => markCovers(m, mark)))) all = false;
332
+ });
333
+ return found && all;
616
334
  }
335
+ return false;
617
336
  }
618
- function nextElement(el) {
619
- let next = el.nextSibling;
620
- while (next && next.nodeType === Node.TEXT_NODE && !next.textContent?.trim())
621
- next = next.nextSibling;
622
- return next instanceof Element ? next : null;
337
+ function markCovers(m, mark) {
338
+ if (m.type !== mark.type) return false;
339
+ if (mark.type.name === "span_class")
340
+ return hasClasses(m.attrs.class, classList(mark.attrs.class));
341
+ return mark.attrs.value === void 0 || m.attrs.value === mark.attrs.value;
623
342
  }
624
- function buildNestedList(run) {
625
- const doc = run[0].el.ownerDocument;
626
- const anchor = run[0].el;
627
- const stack = [];
628
- let top = null;
629
- for (const item of run) {
630
- while (stack.length && stack[stack.length - 1].level > item.level) stack.pop();
631
- let current = stack[stack.length - 1];
632
- if (!current || current.level < item.level) {
633
- const list = doc.createElement(item.ordered ? "ol" : "ul");
634
- if (item.ordered && item.start !== 1) list.setAttribute("start", String(item.start));
635
- if (item.style) list.style.listStyleType = item.style;
636
- if (current) {
637
- const parentItem = current.list.lastElementChild ?? current.list.appendChild(doc.createElement("li"));
638
- parentItem.appendChild(list);
639
- } else top = list;
640
- current = { list, level: item.level };
641
- stack.push(current);
343
+ function applySpec(state, tr, spec) {
344
+ const classes = classList(spec.classes);
345
+ const nodes = nodesOf(state);
346
+ if (spec.block === "blockquote") {
347
+ const quote = blockquoteAt(state);
348
+ if (quote) {
349
+ tr.setNodeMarkup(quote.pos, void 0, {
350
+ ...quote.node.attrs,
351
+ class: withClasses(quote.node.attrs.class, classes)
352
+ });
353
+ return true;
642
354
  }
643
- const li = doc.createElement("li");
644
- const p = doc.createElement("p");
645
- while (item.el.firstChild) p.appendChild(item.el.firstChild);
646
- li.appendChild(p);
647
- current.list.appendChild(li);
648
- }
649
- anchor.replaceWith(top);
650
- run.slice(1).forEach((item) => item.el.remove());
651
- }
652
- function levelOf(li) {
653
- const raw = li.getAttribute("aria-level") ?? li.getAttribute("data-aria-level");
654
- const n = raw ? Number(raw) : NaN;
655
- return Number.isFinite(n) && n >= 1 ? Math.min(9, n) : null;
656
- }
657
- function normalizeLists(root) {
658
- root.querySelectorAll("div").forEach((div) => {
659
- const only = div.children.length === 1 ? div.firstElementChild : null;
660
- if (only && /^(UL|OL)$/.test(only.tagName) && !div.textContent?.replace(only.textContent ?? "", "").trim())
661
- unwrap(div);
662
- });
663
- root.querySelectorAll("ul > ul, ul > ol, ol > ul, ol > ol").forEach((list) => {
664
- const prev = list.previousElementSibling;
665
- if (prev?.tagName === "LI") prev.appendChild(list);
666
- });
667
- const lists = [...root.querySelectorAll("ul, ol")].filter(
668
- (l) => !l.parentElement?.closest("ul, ol") && l.querySelector("li[aria-level], li[data-aria-level]")
669
- );
670
- const done = /* @__PURE__ */ new Set();
671
- for (const first of lists) {
672
- if (done.has(first) || !root.contains(first)) continue;
673
- const run = [];
674
- let node = first;
675
- while (node && /^(UL|OL)$/.test(node.tagName)) {
676
- done.add(node);
677
- collectListItems(node, 1, run);
678
- const next = nextElement(node);
679
- if (node !== first) node.remove();
680
- node = next;
355
+ return wrapIn(nodes.blockquote, { class: withClasses(null, classes) })(
356
+ state,
357
+ (wrapped2) => wrapped2.steps.forEach((step) => tr.step(step))
358
+ );
359
+ }
360
+ if (spec.block === "pre") {
361
+ for (const { node, pos } of textBlocks(state)) {
362
+ if (node.type !== nodes.code_block)
363
+ tr.setNodeMarkup(pos, nodes.code_block, { language: null });
681
364
  }
682
- if (!run.length) continue;
683
- const placeholder = first.ownerDocument.createElement("div");
684
- first.replaceWith(placeholder);
685
- buildNestedListFromBlocks(run, placeholder);
365
+ return true;
686
366
  }
687
- }
688
- function collectListItems(list, depth, run) {
689
- for (const li of [...list.children]) {
690
- if (li.tagName !== "LI") continue;
691
- const level = levelOf(li) ?? depth;
692
- const nested = [...li.children].filter((c) => /^(UL|OL)$/.test(c.tagName));
693
- nested.forEach((n) => n.remove());
694
- const holder = li.ownerDocument.createElement("div");
695
- while (li.firstChild) holder.appendChild(li.firstChild);
696
- run.push({
697
- el: holder,
698
- level,
699
- ordered: list.tagName === "OL",
700
- start: Number(list.getAttribute("start") ?? 1) || 1
701
- });
702
- nested.forEach((n) => collectListItems(n, level + 1, run));
367
+ if (spec.block) {
368
+ const level = spec.block === "p" ? 0 : Number(spec.block.slice(1));
369
+ const type = level ? nodes.heading : nodes.paragraph;
370
+ const styles = blockStyles(spec);
371
+ for (const { node, pos } of textBlocks(state)) {
372
+ if (node.type === nodes.code_block && node.textContent.includes("\n")) continue;
373
+ const sameType = node.type === type && (!level || node.attrs.level === level);
374
+ tr.setNodeMarkup(pos, type, {
375
+ ...keepBlockStyle(node.attrs),
376
+ ...level ? { level } : {},
377
+ ...styles,
378
+ class: withClasses(sameType ? node.attrs.class : null, classes)
379
+ });
380
+ }
381
+ return true;
703
382
  }
704
- }
705
- function buildNestedListFromBlocks(run, placeholder) {
706
- const doc = placeholder.ownerDocument;
707
- const stack = [];
708
- let top = null;
709
- for (const item of run) {
710
- while (stack.length && stack[stack.length - 1].level > item.level) stack.pop();
711
- let current = stack[stack.length - 1];
712
- if (!current || current.level < item.level) {
713
- const list = doc.createElement(item.ordered ? "ol" : "ul");
714
- if (item.ordered && item.start !== 1 && !current)
715
- list.setAttribute("start", String(item.start));
716
- if (current) {
717
- const parentItem = current.list.lastElementChild ?? current.list.appendChild(doc.createElement("li"));
718
- parentItem.appendChild(list);
719
- } else top = list;
720
- current = { list, level: item.level };
721
- stack.push(current);
383
+ if (spec.selector) {
384
+ const styles = blockStyles(spec);
385
+ const targets = selectedNodes(state, selectorTags(spec));
386
+ if (!targets.length) return false;
387
+ for (const { node, pos } of targets) {
388
+ const extra = node.type.name === "image" ? {} : styles;
389
+ tr.setNodeMarkup(pos, void 0, {
390
+ ...node.attrs,
391
+ ...extra,
392
+ class: withClasses(node.attrs.class, classes)
393
+ });
722
394
  }
723
- const li = doc.createElement("li");
724
- while (item.el.firstChild) li.appendChild(item.el.firstChild);
725
- current.list.appendChild(li);
395
+ if (state.selection instanceof NodeSelection)
396
+ tr.setSelection(NodeSelection.create(tr.doc, state.selection.from));
397
+ return true;
726
398
  }
727
- placeholder.replaceWith(top);
728
- }
729
- function unwrapGoogleDocsWrapper(root) {
730
- root.querySelectorAll('[id^="docs-internal-guid-"]').forEach(unwrap);
731
- root.querySelectorAll('li[role="checkbox"]').forEach((li) => {
732
- li.removeAttribute("role");
733
- li.removeAttribute("aria-checked");
734
- });
735
- }
736
- function convertWordParagraphStyles(root) {
737
- root.querySelectorAll('p.MsoTitle, p[class*="Title"]').forEach((p) => {
738
- if (!/\bMsoTitle\b|^Title$/.test(p.className)) return;
739
- renameElement(p, "h1");
740
- });
741
- root.querySelectorAll('div.WordSection1, div[class^="WordSection"], div.Section1').forEach(unwrap);
399
+ if (spec.inline) {
400
+ const marks = inlineMarks(state, spec);
401
+ if (!marks.length) return false;
402
+ const { empty, ranges } = state.selection;
403
+ if (empty) {
404
+ let stored = state.storedMarks ?? state.selection.$from.marks();
405
+ for (const mark of marks) stored = mark.addToSet(stored);
406
+ tr.setStoredMarks(stored);
407
+ return true;
408
+ }
409
+ for (const { $from, $to } of ranges) {
410
+ for (const mark of marks) tr.addMark($from.pos, $to.pos, mark);
411
+ }
412
+ return true;
413
+ }
414
+ return false;
742
415
  }
743
- var DEFAULT_TEXT_COLORS = /^(black|windowtext|auto|#000|#000000|rgb\(0,\s*0,\s*0\)|initial|inherit)$/i;
744
- 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;
745
- 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;
746
- function cleanStyle(el, mode) {
747
- const decls = parseDeclarations(el.getAttribute("style") ?? "");
748
- const out = /* @__PURE__ */ new Map();
749
- decls.forEach((value, name) => {
750
- if (name.startsWith("mso-")) {
751
- if (name === "mso-highlight" && !DEFAULT_BACKGROUNDS.test(value) && !decls.has("background-color"))
752
- out.set("background-color", value);
416
+ function removeSpec(state, tr, spec) {
417
+ const classes = classList(spec.classes);
418
+ const nodes = nodesOf(state);
419
+ if (spec.block === "blockquote") {
420
+ const quote = blockquoteAt(state);
421
+ if (!quote) return;
422
+ const rest = withoutClasses(quote.node.attrs.class, classes);
423
+ if (classes.length && rest !== null) {
424
+ tr.setNodeMarkup(quote.pos, void 0, { ...quote.node.attrs, class: rest });
753
425
  return;
754
426
  }
755
- if (name.startsWith("-webkit-") || name.startsWith("-moz-")) return;
756
- if (name === "background") {
757
- const color2 = value.split(/\s+/)[0];
758
- if (/^(#[0-9a-f]{3,8}|rgba?\([^)]*\)|[a-z]+)$/i.test(color2) && !out.has("background-color"))
759
- out.set("background-color", color2);
760
- return;
427
+ lift(state, (lifted) => lifted.steps.forEach((step) => tr.step(step)));
428
+ return;
429
+ }
430
+ if (spec.block) {
431
+ for (const { node, pos } of textBlocks(state)) {
432
+ if (!BLOCK_TAGS[spec.block](node)) continue;
433
+ tr.setNodeMarkup(pos, nodes.paragraph, {
434
+ ...keepBlockStyle(node.attrs),
435
+ class: spec.block === "p" ? withoutClasses(node.attrs.class, classes) : null
436
+ });
761
437
  }
762
- if (name === "text-decoration" || name === "text-decoration-line") {
763
- if (/underline/.test(value)) out.set("text-decoration", "underline");
764
- else if (/line-through/.test(value)) out.set("text-decoration", "line-through");
765
- return;
438
+ return;
439
+ }
440
+ if (spec.selector) {
441
+ const styles = blockStyles(spec);
442
+ for (const { node, pos } of selectedNodes(state, selectorTags(spec))) {
443
+ const reset = {};
444
+ if (node.type.name !== "image") {
445
+ if ("align" in styles && node.attrs.align === styles.align) reset.align = null;
446
+ if ("lineHeight" in styles && node.attrs.lineHeight === styles.lineHeight)
447
+ reset.lineHeight = null;
448
+ }
449
+ tr.setNodeMarkup(pos, void 0, {
450
+ ...node.attrs,
451
+ ...reset,
452
+ class: withoutClasses(node.attrs.class, classes)
453
+ });
766
454
  }
767
- if (mode === "clean" && CLEAN_DROP.test(name)) return;
768
- if (mode === "clean" && name === "vertical-align" && /^(TD|TH)$/.test(el.tagName)) return;
769
- out.set(name, value);
770
- });
771
- const color = out.get("color");
772
- if (color && DEFAULT_TEXT_COLORS.test(color.trim()) && mode === "clean") out.delete("color");
773
- const background = out.get("background-color");
774
- if (background && DEFAULT_BACKGROUNDS.test(background.trim())) out.delete("background-color");
775
- if (out.get("font-weight") === "normal" && el.tagName !== "B") out.delete("font-weight");
776
- if (out.get("font-style") === "normal") out.delete("font-style");
777
- if (out.get("text-decoration") === "none") out.delete("text-decoration");
778
- if (out.get("vertical-align") === "baseline") out.delete("vertical-align");
779
- if (/^(left|start)$/i.test(out.get("text-align") ?? "")) out.delete("text-align");
780
- if (mode === "clean" && el.closest("a")) {
781
- out.delete("color");
782
- if (out.get("text-decoration") === "underline") out.delete("text-decoration");
783
- }
784
- if (out.size) el.setAttribute("style", serializeDeclarations(out));
785
- else el.removeAttribute("style");
786
- }
787
- function stripLayoutAttributes(root) {
788
- root.querySelectorAll("table, tr, td, th, col, colgroup").forEach((el) => {
789
- el.removeAttribute("width");
790
- el.removeAttribute("height");
791
- el.removeAttribute("valign");
792
- });
793
- }
794
- function unwrapMeaningless(root) {
795
- for (const el of [...root.querySelectorAll("span, font")].reverse()) {
796
- if (!root.contains(el)) continue;
797
- const hasFormatting = el.hasAttribute("style") || el.tagName === "FONT" && el.hasAttribute("color");
798
- if (!hasFormatting) unwrap(el);
799
- }
800
- root.querySelectorAll("[class]").forEach((el) => el.removeAttribute("class"));
801
- root.querySelectorAll("[lang]").forEach((el) => el.removeAttribute("lang"));
802
- root.querySelectorAll("[dir]").forEach((el) => {
803
- if (!/^rtl$/i.test(el.getAttribute("dir") ?? "")) el.removeAttribute("dir");
804
- });
805
- }
806
- var BLOCK = /^(P|DIV|H[1-6]|UL|OL|TABLE|BLOCKQUOTE|PRE|HR)$/;
807
- function removeBreaksBetweenBlocks(root) {
808
- root.querySelectorAll("br").forEach((br) => {
809
- const parent = br.parentElement;
810
- if (!parent || !(parent === root || parent.tagName === "DIV" || parent.tagName === "TD" || parent.tagName === "LI"))
455
+ if (state.selection instanceof NodeSelection)
456
+ tr.setSelection(NodeSelection.create(tr.doc, state.selection.from));
457
+ return;
458
+ }
459
+ if (spec.inline) {
460
+ const marks = inlineMarks(state, spec);
461
+ const { empty, from, to, $from } = state.selection;
462
+ if (empty) {
463
+ const stored = (state.storedMarks ?? $from.marks()).filter(
464
+ (m) => !marks.some((mark) => markCovers(m, mark))
465
+ );
466
+ tr.setStoredMarks(stored);
811
467
  return;
812
- const prev = siblingElement(br, -1);
813
- const next = siblingElement(br, 1);
814
- if (prev && BLOCK.test(prev.tagName) || next && BLOCK.test(next.tagName) || !prev && !next && parent === root)
815
- br.remove();
816
- });
817
- }
818
- function siblingElement(node, dir) {
819
- let s = dir < 0 ? node.previousSibling : node.nextSibling;
820
- while (s && s.nodeType === Node.TEXT_NODE && !s.textContent?.trim())
821
- s = dir < 0 ? s.previousSibling : s.nextSibling;
822
- return s instanceof Element ? s : null;
823
- }
824
- function normalizeEmptyParagraphs(root) {
825
- root.querySelectorAll("p").forEach((p) => {
826
- if (p.children.length === 0 && /^\s*$/.test(p.textContent ?? "")) p.textContent = "";
827
- });
828
- }
829
- function wrapCellContent(root) {
830
- root.querySelectorAll("td, th").forEach((cell) => {
831
- const align = cell.style.textAlign;
832
- const hasBlock = [...cell.children].some((c) => BLOCK.test(c.tagName));
833
- if (!align || hasBlock || !cell.textContent?.trim()) return;
834
- const p = cell.ownerDocument.createElement("p");
835
- p.style.textAlign = align;
836
- while (cell.firstChild) p.appendChild(cell.firstChild);
837
- cell.appendChild(p);
838
- cell.style.removeProperty("text-align");
839
- if (!cell.getAttribute("style")) cell.removeAttribute("style");
840
- });
841
- }
842
- function unwrap(el) {
843
- const parent = el.parentNode;
844
- if (!parent) return;
845
- while (el.firstChild) parent.insertBefore(el.firstChild, el);
846
- parent.removeChild(el);
847
- }
848
- function renameElement(el, tag) {
849
- const next = el.ownerDocument.createElement(tag);
850
- for (const attr of [...el.attributes]) next.setAttribute(attr.name, attr.value);
851
- while (el.firstChild) next.appendChild(el.firstChild);
852
- el.replaceWith(next);
853
- return next;
468
+ }
469
+ for (const mark of marks) {
470
+ if (mark.type.name !== "span_class") {
471
+ tr.removeMark(from, to, mark.type);
472
+ continue;
473
+ }
474
+ state.doc.nodesBetween(from, to, (node, pos) => {
475
+ if (!node.isText) return;
476
+ const current = node.marks.find((m) => m.type === mark.type);
477
+ if (!current) return;
478
+ const start = Math.max(pos, from);
479
+ const end = Math.min(pos + node.nodeSize, to);
480
+ tr.removeMark(start, end, mark.type);
481
+ const rest = withoutClasses(current.attrs.class, classList(mark.attrs.class));
482
+ if (rest) tr.addMark(start, end, mark.type.create({ class: rest }));
483
+ });
484
+ }
485
+ }
854
486
  }
855
487
 
488
+ // src/paste.ts
489
+ import { Slice } from "prosemirror-model";
490
+ import { Plugin, PluginKey } from "prosemirror-state";
491
+
856
492
  // src/paste-rtf.ts
857
493
  function groupEnd(rtf, start) {
858
494
  let depth = 0;
@@ -935,6 +571,18 @@ function replaceLocalImages(html, images) {
935
571
  }
936
572
 
937
573
  // src/paste.ts
574
+ var cleaner = null;
575
+ var loading = null;
576
+ function loadPasteCleaner() {
577
+ loading ??= import("./paste-office-F3QW4WWO.js").then(
578
+ (module) => cleaner = module,
579
+ () => {
580
+ loading = null;
581
+ return null;
582
+ }
583
+ );
584
+ return loading;
585
+ }
938
586
  var key = new PluginKey("nova-paste");
939
587
  function htmlToPlainText(html) {
940
588
  const template = document.createElement("template");
@@ -984,7 +632,7 @@ function pastePlugin(editor) {
984
632
  transformPastedHTML(html) {
985
633
  const { pastePreprocess, pastePostprocess, pasteStyles } = editor.options;
986
634
  let result = pastePreprocess ? pastePreprocess(html, editor) : html;
987
- result = cleanPastedHTML(result, pasteStyles ?? "clean");
635
+ if (cleaner) result = cleaner.cleanPastedHTML(result, pasteStyles ?? "clean");
988
636
  if (pastePostprocess) {
989
637
  const template = document.createElement("template");
990
638
  template.innerHTML = result;
@@ -995,6 +643,32 @@ function pastePlugin(editor) {
995
643
  }
996
644
  return result;
997
645
  },
646
+ handleDOMEvents: {
647
+ /**
648
+ * Вставка HTML раньше, чем догрузилась очистка (первые миллисекунды после создания или
649
+ * медленная сеть): забираем данные буфера сейчас (после события они недоступны), ждём чанк
650
+ * и вставляем как обычно — через transformPastedHTML уже с очисткой.
651
+ */
652
+ paste(view, event) {
653
+ if (cleaner || reentrant || editor.isPasteAsText()) return false;
654
+ const data = event.clipboardData;
655
+ const html = data?.getData("text/html");
656
+ if (!html) return false;
657
+ const rtf = hasLocalFileImages(html) ? data?.getData("text/rtf") ?? "" : "";
658
+ event.preventDefault();
659
+ void loadPasteCleaner().then(() => {
660
+ if (view.isDestroyed) return;
661
+ const withImages = rtf && editor.isAllowed("image") ? replaceLocalImages(html, extractRtfImages(rtf)) : html;
662
+ reentrant = true;
663
+ try {
664
+ view.pasteHTML(withImages);
665
+ } finally {
666
+ reentrant = false;
667
+ }
668
+ });
669
+ return true;
670
+ }
671
+ },
998
672
  handlePaste(view, event, slice) {
999
673
  if (reentrant) return false;
1000
674
  const html = event.clipboardData?.getData("text/html");
@@ -1030,8 +704,22 @@ import {
1030
704
  DOMParser
1031
705
  } from "prosemirror-model";
1032
706
  var CELL_BG_ATTR = "data-nova-cell-bg";
707
+ var HTML_NS = "http://www.w3.org/1999/xhtml";
708
+ var MATHML_NS = "http://www.w3.org/1998/Math/MathML";
709
+ function replaceForeignElements(root) {
710
+ const foreign = [...root.querySelectorAll("*")].filter(
711
+ // Только самые внешние: родитель — HTML-элемент или сам фрагмент (parentElement = null).
712
+ (el) => el.namespaceURI !== HTML_NS && (el.parentElement?.namespaceURI ?? HTML_NS) === HTML_NS
713
+ );
714
+ for (const el of foreign) {
715
+ const text = el.namespaceURI === MATHML_NS ? el.textContent ?? "" : "";
716
+ el.replaceWith(el.ownerDocument.createTextNode(text));
717
+ }
718
+ }
1033
719
  function preprocessDOM(root) {
720
+ replaceForeignElements(root);
1034
721
  root.querySelectorAll("td, th").forEach((cell) => {
722
+ if (!cell.style) return;
1035
723
  const bg = cell.style.backgroundColor;
1036
724
  if (!bg) return;
1037
725
  cell.setAttribute(CELL_BG_ATTR, bg);
@@ -1040,12 +728,31 @@ function preprocessDOM(root) {
1040
728
  });
1041
729
  }
1042
730
  var NovaDOMParser = class extends DOMParser {
1043
- parse(dom, options) {
731
+ atomSelector;
732
+ ownStyleSelector;
733
+ prepare(dom) {
1044
734
  preprocessDOM(dom);
735
+ this.ownStyleSelector ??= Object.values(this.schema.nodes).flatMap((type) => type.spec.ownStyleTags ?? []).join(", ");
736
+ if (this.ownStyleSelector && "querySelectorAll" in dom) {
737
+ dom.querySelectorAll(this.ownStyleSelector).forEach((el) => {
738
+ const style = el.getAttribute("style");
739
+ if (style === null) return;
740
+ el.setAttribute(OWN_STYLE, style);
741
+ el.removeAttribute("style");
742
+ });
743
+ }
744
+ this.atomSelector ??= Object.values(this.schema.nodes).filter((type) => type.spec.ignoreStyles).flatMap((type) => (type.spec.parseDOM ?? []).map((rule) => rule.tag)).filter((tag) => !!tag).join(", ");
745
+ if (!this.atomSelector || !("querySelectorAll" in dom)) return;
746
+ dom.querySelectorAll(this.atomSelector).forEach((el) => {
747
+ el.removeAttribute("style");
748
+ });
749
+ }
750
+ parse(dom, options) {
751
+ this.prepare(dom);
1045
752
  return super.parse(dom, options);
1046
753
  }
1047
754
  parseSlice(dom, options) {
1048
- preprocessDOM(dom);
755
+ this.prepare(dom);
1049
756
  return super.parseSlice(dom, options);
1050
757
  }
1051
758
  };
@@ -1064,12 +771,18 @@ var novaParser = parserFor(schema);
1064
771
  function createMenu(entries, onDone, label) {
1065
772
  const items = [];
1066
773
  const menu = h("div", { className: "nova-menu", role: "menu", "aria-label": label });
1067
- const hasChecks = entries.some((e) => e.type !== "separator" && e.active !== void 0);
774
+ const hasChecks = entries.some(
775
+ (e) => (e.type === void 0 || e.type === "item") && e.active !== void 0
776
+ );
1068
777
  for (const entry of entries) {
1069
778
  if (entry.type === "separator") {
1070
779
  menu.append(h("div", { className: "nova-menu-sep", role: "separator" }));
1071
780
  continue;
1072
781
  }
782
+ if (entry.type === "heading") {
783
+ menu.append(h("div", { className: "nova-menu-heading", role: "presentation" }, entry.label));
784
+ continue;
785
+ }
1073
786
  const labelEl = h("span", { className: "nova-menu-label" }, entry.label);
1074
787
  if (entry.labelStyle) labelEl.setAttribute("style", entry.labelStyle);
1075
788
  const button = h(
@@ -1103,7 +816,7 @@ function createMenu(entries, onDone, label) {
1103
816
  };
1104
817
  menu.addEventListener("keydown", (event) => {
1105
818
  const list = enabled();
1106
- const current = list.indexOf(document.activeElement);
819
+ const current = list.indexOf(activeElement(menu));
1107
820
  switch (event.key) {
1108
821
  case "ArrowDown":
1109
822
  event.preventDefault();
@@ -1204,9 +917,10 @@ function createMenubar(editor, host, config, menus) {
1204
917
  if (!items.length) return;
1205
918
  const menu = createMenu(items, () => editor.ui.closePopover(), title(def));
1206
919
  menu.addEventListener("keydown", (event) => {
1207
- if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
920
+ const key3 = logicalKey(event, menu);
921
+ if (key3 !== "ArrowLeft" && key3 !== "ArrowRight") return;
1208
922
  event.preventDefault();
1209
- const next = (index + (event.key === "ArrowRight" ? 1 : -1) + buttons.length) % buttons.length;
923
+ const next = (index + (key3 === "ArrowRight" ? 1 : -1) + buttons.length) % buttons.length;
1210
924
  openMenu(next, true);
1211
925
  });
1212
926
  button.setAttribute("aria-expanded", "true");
@@ -1254,7 +968,7 @@ function createMenubar(editor, host, config, menus) {
1254
968
  host.addEventListener(
1255
969
  "keydown",
1256
970
  (event) => {
1257
- const index = buttons.indexOf(document.activeElement);
971
+ const index = buttons.indexOf(activeElement(host));
1258
972
  if (index < 0) return;
1259
973
  const move = (to) => {
1260
974
  event.preventDefault();
@@ -1262,8 +976,9 @@ function createMenubar(editor, host, config, menus) {
1262
976
  buttons.forEach((b, i) => b.tabIndex = i === next ? 0 : -1);
1263
977
  buttons[next].focus();
1264
978
  };
1265
- if (event.key === "ArrowRight") move(index + 1);
1266
- else if (event.key === "ArrowLeft") move(index - 1);
979
+ const key3 = logicalKey(event, host);
980
+ if (key3 === "ArrowRight") move(index + 1);
981
+ else if (key3 === "ArrowLeft") move(index - 1);
1267
982
  else if (event.key === "Home") move(0);
1268
983
  else if (event.key === "End") move(buttons.length - 1);
1269
984
  else if (event.key === "ArrowDown") {
@@ -1395,7 +1110,8 @@ var ALIASES = {
1395
1110
  tfoot: "table",
1396
1111
  caption: "table",
1397
1112
  colgroup: "table",
1398
- col: "table"
1113
+ col: "table",
1114
+ figcaption: "figure"
1399
1115
  };
1400
1116
  var KNOWN_TAGS = [
1401
1117
  "p",
@@ -1412,6 +1128,7 @@ var KNOWN_TAGS = [
1412
1128
  "ol",
1413
1129
  "li",
1414
1130
  "img",
1131
+ "figure",
1415
1132
  "br",
1416
1133
  "table",
1417
1134
  "tr",
@@ -1521,6 +1238,7 @@ var ContentRules = class {
1521
1238
  const valid = parseList(options.validElements);
1522
1239
  const invalid = parseList(options.invalidElements) ?? /* @__PURE__ */ new Set();
1523
1240
  const tags = new Set(valid ?? KNOWN_TAGS);
1241
+ if (valid) for (const tag of parseList(options.extendedValidElements) ?? []) tags.add(tag);
1524
1242
  if (tags.has("ul") || tags.has("ol")) tags.add("li");
1525
1243
  if (tags.has("table")) {
1526
1244
  tags.add("tr");
@@ -1581,7 +1299,8 @@ var ContentRules = class {
1581
1299
  return {
1582
1300
  ...attrs,
1583
1301
  ...this.isStyleAllowed("text-align") ? {} : { align: null },
1584
- ...this.isStyleAllowed("line-height") ? {} : { lineHeight: null }
1302
+ ...this.isStyleAllowed("line-height") ? {} : { lineHeight: null },
1303
+ ...this.isStyleAllowed("margin-left") ? {} : { indent: 0 }
1585
1304
  };
1586
1305
  }
1587
1306
  /** Привести узел к правилам. Возвращает 0…n узлов (запрещённый блок может «раствориться»). */
@@ -1603,6 +1322,18 @@ var ContentRules = class {
1603
1322
  marks
1604
1323
  )
1605
1324
  ];
1325
+ case nodes.figure: {
1326
+ const caption = node.childCount > 1 ? node.child(1).content : null;
1327
+ const captionBlocks = caption?.size ? [nodes.paragraph.create(null, this.normalizeChildren(caption))] : [];
1328
+ const image = node.firstChild;
1329
+ if (!this.isTagAllowed("img") || !image) return captionBlocks;
1330
+ const align = this.isStyleAllowed("float") ? node.attrs.align : null;
1331
+ if (!this.isTagAllowed("figure")) {
1332
+ const inline = nodes.image.create({ ...image.attrs, align });
1333
+ return [nodes.paragraph.create(null, inline), ...captionBlocks];
1334
+ }
1335
+ return [nodes.figure.create({ ...node.attrs, align }, node.content)];
1336
+ }
1606
1337
  case nodes.hard_break:
1607
1338
  return this.isTagAllowed("br") ? [node.mark(marks)] : [schema2.text(" ", marks)];
1608
1339
  case nodes.horizontal_rule:
@@ -1955,7 +1686,9 @@ var SHORTCUTS = [
1955
1686
  { label: "h3", keys: "Mod-Alt-3" },
1956
1687
  { label: "bulletList", keys: "Mod-Shift-8" },
1957
1688
  { label: "orderedList", keys: "Mod-Shift-7" },
1958
- { label: "alignCenter", keys: "Mod-Shift-e" }
1689
+ { label: "alignCenter", keys: "Mod-Shift-e" },
1690
+ { label: "indent", keys: "Mod-]" },
1691
+ { label: "outdent", keys: "Mod-[" }
1959
1692
  ]
1960
1693
  },
1961
1694
  {
@@ -2032,6 +1765,41 @@ var NBSP = new RegExp(String.fromCharCode(160), "g");
2032
1765
  function escapeText(text) {
2033
1766
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(NBSP, "&nbsp;");
2034
1767
  }
1768
+ var NBSP_CHAR = "\xA0";
1769
+ function protectSpaces(fragment) {
1770
+ let result = null;
1771
+ let collapsible = true;
1772
+ const count = fragment.childCount;
1773
+ for (let i = 0; i < count; i++) {
1774
+ const node = fragment.child(i);
1775
+ if (!node.isText) {
1776
+ collapsible = node.type.name === "hard_break" || !node.isInline;
1777
+ continue;
1778
+ }
1779
+ const text = node.text ?? "";
1780
+ if (!text.includes(" ")) {
1781
+ collapsible = false;
1782
+ continue;
1783
+ }
1784
+ const lineEndsAfter = i === count - 1 || !fragment.child(i + 1).isInline;
1785
+ let out = "";
1786
+ for (let k = 0; k < text.length; k++) {
1787
+ const ch = text[k];
1788
+ if (ch !== " ") {
1789
+ out += ch;
1790
+ collapsible = false;
1791
+ } else if (collapsible || lineEndsAfter && k === text.length - 1) {
1792
+ out += NBSP_CHAR;
1793
+ collapsible = false;
1794
+ } else {
1795
+ out += " ";
1796
+ collapsible = true;
1797
+ }
1798
+ }
1799
+ if (out !== text) (result ??= /* @__PURE__ */ new Map()).set(i, out);
1800
+ }
1801
+ return result;
1802
+ }
2035
1803
  function escapeAttr(value) {
2036
1804
  return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(NBSP, "&nbsp;");
2037
1805
  }
@@ -2050,21 +1818,6 @@ var FORBIDDEN_TAGS = /* @__PURE__ */ new Set([
2050
1818
  "template",
2051
1819
  "noscript"
2052
1820
  ]);
2053
- var LINK_ATTRS = /* @__PURE__ */ new Set(["href", "xlink:href", "action", "formaction", "cite"]);
2054
- var RESOURCE_ATTRS = /* @__PURE__ */ new Set(["src", "poster", "data", "background"]);
2055
- var UNSAFE_CSS = /url\s*\(|expression\s*\(|javascript:|@import|behavior\s*:|-moz-binding/i;
2056
- function safeAttr(name, value) {
2057
- const lower = name.toLowerCase();
2058
- if (lower.startsWith("on")) return null;
2059
- if (LINK_ATTRS.has(lower)) return isSafeLinkUrl(value) ? value : null;
2060
- if (RESOURCE_ATTRS.has(lower)) return isSafeImageUrl(value) ? value : null;
2061
- if (lower === "srcset") {
2062
- const urls = value.split(",").map((part) => part.trim().split(/\s+/)[0] ?? "");
2063
- return urls.every((url) => isSafeImageUrl(url)) ? value : null;
2064
- }
2065
- if (lower === "style") return UNSAFE_CSS.test(value) ? null : value;
2066
- return value;
2067
- }
2068
1821
  var reported = /* @__PURE__ */ new Set();
2069
1822
  function reportForbidden(tag) {
2070
1823
  if (reported.has(tag)) return;
@@ -2076,6 +1829,10 @@ function reportForbidden(tag) {
2076
1829
  var ATTR_RE = /^[a-z_:][a-z0-9_.:-]*$/i;
2077
1830
  function renderSpec(spec) {
2078
1831
  if (typeof spec === "string") return { open: "", close: "", hole: false, html: escapeText(spec) };
1832
+ if (typeof spec === "number" || typeof spec === "boolean") {
1833
+ return { open: "", close: "", hole: false, html: escapeText(String(spec)) };
1834
+ }
1835
+ if (spec == null) return { open: "", close: "", hole: false, html: "" };
2079
1836
  if (!Array.isArray(spec)) {
2080
1837
  throw new Error("[nova] serializer supports only array/string toDOM specs");
2081
1838
  }
@@ -2128,8 +1885,13 @@ function renderSpec(spec) {
2128
1885
  return { open: open + before, close: after + close, hole, html: open + before + after + close };
2129
1886
  }
2130
1887
  var HTMLSerializer = class {
2131
- cache = /* @__PURE__ */ new Map();
2132
- serializeFragment(fragment) {
1888
+ /**
1889
+ * Кэш отрисовки марок — свой у каждого типа марки: сериализатор общий для всех редакторов страницы,
1890
+ * а вывод одноимённой марки зависит от схемы редактора (правила атрибутов, плагины).
1891
+ */
1892
+ cache = /* @__PURE__ */ new WeakMap();
1893
+ serializeFragment(fragment, { pre = false } = {}) {
1894
+ const texts = pre ? null : protectSpaces(fragment);
2133
1895
  let out = "";
2134
1896
  let active = [];
2135
1897
  let closers = [];
@@ -2139,7 +1901,7 @@ var HTMLSerializer = class {
2139
1901
  active.pop();
2140
1902
  }
2141
1903
  };
2142
- fragment.forEach((node) => {
1904
+ fragment.forEach((node, _offset, index) => {
2143
1905
  if (!node.isInline) {
2144
1906
  closeTo(0);
2145
1907
  out += this.serializeNode(node);
@@ -2156,7 +1918,7 @@ var HTMLSerializer = class {
2156
1918
  closers.push(r.close);
2157
1919
  active.push(mark);
2158
1920
  }
2159
- out += node.isText ? escapeText(node.text ?? "") : this.serializeNode(node);
1921
+ out += node.isText ? escapeText(texts?.get(index) ?? node.text ?? "") : this.serializeNode(node);
2160
1922
  });
2161
1923
  closeTo(0);
2162
1924
  active = [];
@@ -2168,17 +1930,20 @@ var HTMLSerializer = class {
2168
1930
  if (!toDOM) throw new Error(`[nova] node "${node.type.name}" has no toDOM`);
2169
1931
  const r = renderSpec(toDOM(node));
2170
1932
  if (!r.hole) return r.html;
2171
- return r.open + this.serializeFragment(node.content) + r.close;
1933
+ const pre = !!node.type.spec.code || node.type.spec.whitespace === "pre";
1934
+ return r.open + this.serializeFragment(node.content, { pre }) + r.close;
2172
1935
  }
2173
1936
  renderMark(mark, inline) {
2174
1937
  const toDOM = mark.type.spec.toDOM;
2175
1938
  if (!toDOM) throw new Error(`[nova] mark "${mark.type.name}" has no toDOM`);
2176
- const key3 = `${mark.type.name}:${JSON.stringify(mark.attrs)}`;
2177
- let r = this.cache.get(key3);
1939
+ let cache = this.cache.get(mark.type);
1940
+ if (!cache) this.cache.set(mark.type, cache = /* @__PURE__ */ new Map());
1941
+ const key3 = JSON.stringify(mark.attrs);
1942
+ let r = cache.get(key3);
2178
1943
  if (!r) {
2179
1944
  r = renderSpec(toDOM(mark, inline));
2180
- if (this.cache.size > 500) this.cache.clear();
2181
- this.cache.set(key3, r);
1945
+ if (cache.size > 500) cache.clear();
1946
+ cache.set(key3, r);
2182
1947
  }
2183
1948
  return r;
2184
1949
  }
@@ -2281,6 +2046,7 @@ function createColorPanel(options) {
2281
2046
  const swatches = [];
2282
2047
  const current = options.current?.toLowerCase() ?? null;
2283
2048
  const grid = h("div", { className: "nova-swatches", role: "grid", "aria-label": options.label });
2049
+ let row = null;
2284
2050
  for (const color of options.colors) {
2285
2051
  const selected = current === color.toLowerCase();
2286
2052
  const swatch = h(
@@ -2299,14 +2065,18 @@ function createColorPanel(options) {
2299
2065
  swatch.style.setProperty("--swatch", color);
2300
2066
  swatch.addEventListener("click", () => options.onPick(color));
2301
2067
  swatches.push(swatch);
2302
- grid.append(swatch);
2068
+ if (!row || row.childElementCount === COLUMNS) {
2069
+ row = h("div", { className: "nova-swatch-row", role: "row" });
2070
+ grid.append(row);
2071
+ }
2072
+ row.append(swatch);
2303
2073
  }
2304
2074
  (swatches.find((s) => s.getAttribute("aria-selected") === "true") ?? swatches[0])?.setAttribute(
2305
2075
  "tabindex",
2306
2076
  "0"
2307
2077
  );
2308
2078
  grid.addEventListener("keydown", (event) => {
2309
- const index = swatches.indexOf(document.activeElement);
2079
+ const index = swatches.indexOf(activeElement(grid));
2310
2080
  if (index < 0) return;
2311
2081
  const delta = {
2312
2082
  ArrowRight: 1,
@@ -2314,7 +2084,7 @@ function createColorPanel(options) {
2314
2084
  ArrowDown: COLUMNS,
2315
2085
  ArrowUp: -COLUMNS
2316
2086
  };
2317
- const step = delta[event.key];
2087
+ const step = delta[logicalKey(event, grid)];
2318
2088
  if (step === void 0) return;
2319
2089
  event.preventDefault();
2320
2090
  const next = swatches[Math.min(swatches.length - 1, Math.max(0, index + step))];
@@ -2442,6 +2212,15 @@ function registerTableUi(editor) {
2442
2212
  items: "tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol | tablemergecells tablesplitcells | tablerowheader tablecolheader tablecellbackground | advtablesort tablecellprops tableprops | tabledelete"
2443
2213
  });
2444
2214
  }
2215
+ function classSelect(editor, list, current) {
2216
+ if (!list?.length) return null;
2217
+ const { t } = editor.ui;
2218
+ const options = [{ value: "", label: t("table.styleDefault") }];
2219
+ for (const o of list) if (o.value) options.push({ value: o.value, label: o.title });
2220
+ if (current && !options.some((o) => o.value === current))
2221
+ options.push({ value: current, label: current });
2222
+ return selectField({ label: t("table.style"), value: current ?? "", options });
2223
+ }
2445
2224
  function openTableProps(editor) {
2446
2225
  const { t } = editor.ui;
2447
2226
  const current = getTableProps(editor.view.state);
@@ -2460,15 +2239,17 @@ function openTableProps(editor) {
2460
2239
  { value: "right", label: t("table.alignRight") }
2461
2240
  ]
2462
2241
  });
2242
+ const styles = classSelect(editor, editor.options.tableClassList, current.class ?? null);
2463
2243
  editor.ui.openDialog({
2464
2244
  title: t("table.props"),
2465
- body: h("div", { className: "nova-form" }, width.el, align.el),
2245
+ body: h("div", { className: "nova-form" }, styles?.el ?? null, width.el, align.el),
2466
2246
  submitLabel: t("dialog.save"),
2467
2247
  onSubmit: () => {
2468
2248
  const raw = width.input.value.trim().replace(/^(\d+(\.\d+)?)$/, "$1px");
2469
2249
  const props = {
2470
2250
  width: raw || null,
2471
- align: align.select.value || null
2251
+ align: align.select.value || null,
2252
+ ...styles ? { class: styles.select.value || null } : {}
2472
2253
  };
2473
2254
  return editor.exec(setTableProps(props)) || t("table.invalidWidth");
2474
2255
  }
@@ -2501,9 +2282,10 @@ function openCellProps(editor) {
2501
2282
  hint: t("table.colWidthHint"),
2502
2283
  value: current.width ? String(current.width) : ""
2503
2284
  });
2285
+ const styles = classSelect(editor, editor.options.tableCellClassList, current.class ?? null);
2504
2286
  editor.ui.openDialog({
2505
2287
  title: t("table.cellProps"),
2506
- body: h("div", { className: "nova-form" }, valign.el, type.el, width.el),
2288
+ body: h("div", { className: "nova-form" }, styles?.el ?? null, valign.el, type.el, width.el),
2507
2289
  submitLabel: t("dialog.save"),
2508
2290
  onSubmit: () => {
2509
2291
  const rawWidth = width.input.value.trim();
@@ -2514,7 +2296,8 @@ function openCellProps(editor) {
2514
2296
  setCellProps({
2515
2297
  valign: valign.select.value || null,
2516
2298
  header: type.select.value === "th",
2517
- width: px
2299
+ width: px,
2300
+ ...styles ? { class: styles.select.value || null } : {}
2518
2301
  })
2519
2302
  );
2520
2303
  return true;
@@ -2561,6 +2344,8 @@ var SHORTCUTS2 = {
2561
2344
  alignCenter: "Mod-Shift-e",
2562
2345
  alignRight: "Mod-Shift-r",
2563
2346
  alignJustify: "Mod-Shift-j",
2347
+ indent: "Mod-]",
2348
+ outdent: "Mod-[",
2564
2349
  clearFormatting: "Mod-\\",
2565
2350
  paragraph: "Mod-Alt-0",
2566
2351
  h1: "Mod-Alt-1",
@@ -2588,7 +2373,7 @@ var GENERIC_FONTS = {
2588
2373
  "ui-monospace": "Monospace"
2589
2374
  };
2590
2375
  function prettyFontName(family) {
2591
- const first = family.split(",")[0].trim().replace(/["']/g, "");
2376
+ const first = String(family).split(",")[0].trim().replace(/["']/g, "");
2592
2377
  return GENERIC_FONTS[first.toLowerCase()] ?? first;
2593
2378
  }
2594
2379
  function pxToPt(px) {
@@ -2596,7 +2381,7 @@ function pxToPt(px) {
2596
2381
  if (!Number.isFinite(value) || value <= 0) return null;
2597
2382
  return `${Math.round(value * 0.75 * 2) / 2}pt`;
2598
2383
  }
2599
- var sameFont = (a, b) => a !== null && a.replace(/["'\s]/g, "").toLowerCase() === b.replace(/["'\s]/g, "").toLowerCase();
2384
+ var sameFont = (a, b) => typeof a === "string" && a.replace(/["'\s]/g, "").toLowerCase() === b.replace(/["'\s]/g, "").toLowerCase();
2600
2385
  function registerBuiltins(editor) {
2601
2386
  const { registry, t } = editor.ui;
2602
2387
  const state = () => editor.view.state;
@@ -2695,20 +2480,133 @@ function registerBuiltins(editor) {
2695
2480
  onAction: (e) => e.exec(currentBlock() === command ? "paragraph" : command)
2696
2481
  });
2697
2482
  }
2483
+ const BLOCK_COMMANDS = {
2484
+ p: "paragraph",
2485
+ h1: "h1",
2486
+ h2: "h2",
2487
+ h3: "h3",
2488
+ h4: "h4",
2489
+ h5: "h5",
2490
+ h6: "h6",
2491
+ pre: "codeBlock"
2492
+ };
2493
+ const blockList = () => {
2494
+ const custom = editor.options.blockFormats;
2495
+ if (!custom?.length) return blockItems;
2496
+ return custom.flatMap(({ label, block }) => {
2497
+ const command = BLOCK_COMMANDS[block];
2498
+ const item = blockItems.find((i) => i.command === command);
2499
+ return item ? [{ ...item, label }] : [];
2500
+ });
2501
+ };
2698
2502
  registry.addMenuButton("blocks", {
2699
2503
  tooltip: t("blocks"),
2700
- label: () => t(currentBlock()),
2504
+ label: () => blockList().find((i) => i.command === currentBlock())?.label ?? t(currentBlock()),
2701
2505
  minChars: 11,
2702
- isEnabled: (e) => blockItems.some(({ command }) => e.can(command)),
2703
- items: (e) => blockItems.filter(({ command }) => e.isAllowed(command)).map(({ command, style }) => ({
2506
+ isEnabled: (e) => blockList().some(({ command }) => e.can(command)),
2507
+ items: (e) => blockList().filter(({ command }) => e.isAllowed(command)).map(({ command, style, label }) => ({
2704
2508
  id: command,
2705
- label: t(command),
2509
+ label: label ?? t(command),
2706
2510
  labelStyle: style,
2707
2511
  ...SHORTCUTS2[command] ? { shortcut: SHORTCUTS2[command] } : {},
2708
2512
  active: currentBlock() === command,
2709
2513
  onSelect: () => e.exec(command)
2710
2514
  }))
2711
2515
  });
2516
+ const ALIGN_SELECTOR = "p,h1,h2,h3,h4,h5,h6";
2517
+ const defaultStyleFormats = () => [
2518
+ {
2519
+ title: t("styles.headings"),
2520
+ items: [1, 2, 3, 4, 5, 6].map((level) => ({
2521
+ title: t(`h${level}`),
2522
+ block: `h${level}`
2523
+ }))
2524
+ },
2525
+ {
2526
+ title: t("styles.inline"),
2527
+ items: [
2528
+ { title: t("bold"), inline: "strong" },
2529
+ { title: t("italic"), inline: "em" },
2530
+ { title: t("underline"), inline: "u" },
2531
+ { title: t("strike"), inline: "s" },
2532
+ { title: t("superscript"), inline: "sup" },
2533
+ { title: t("subscript"), inline: "sub" },
2534
+ { title: t("code"), inline: "code" }
2535
+ ]
2536
+ },
2537
+ {
2538
+ title: t("styles.blocks"),
2539
+ items: [
2540
+ { title: t("paragraph"), block: "p" },
2541
+ { title: t("blockquote"), block: "blockquote" },
2542
+ { title: t("codeBlock"), block: "pre" }
2543
+ ]
2544
+ },
2545
+ {
2546
+ title: t("styles.align"),
2547
+ items: ["left", "center", "right", "justify"].map((align) => ({
2548
+ title: t(
2549
+ `align${align === "justify" ? "Justify" : align[0].toUpperCase() + align.slice(1)}`
2550
+ ),
2551
+ selector: ALIGN_SELECTOR,
2552
+ styles: { "text-align": align }
2553
+ }))
2554
+ }
2555
+ ];
2556
+ const formatOf = (item) => item.format ?? item;
2557
+ const previewStyle = (item) => {
2558
+ const spec = item.format ? editor.formatter.get(item.format)?.[0] : item;
2559
+ const parts = [];
2560
+ const block = spec?.block;
2561
+ if (block && /^h[1-6]$/.test(block)) parts.push("font-weight: 700");
2562
+ if (spec?.inline === "strong" || spec?.inline === "b") parts.push("font-weight: 700");
2563
+ if (spec?.inline === "em" || spec?.inline === "i") parts.push("font-style: italic");
2564
+ if (spec?.inline === "u") parts.push("text-decoration: underline");
2565
+ if (spec?.inline === "s" || spec?.inline === "strike" || spec?.inline === "del")
2566
+ parts.push("text-decoration: line-through");
2567
+ if (spec?.inline === "code" || block === "pre")
2568
+ parts.push("font-family: ui-monospace, monospace");
2569
+ for (const prop of ["color", "background-color", "font-family"]) {
2570
+ const value = spec?.styles?.[prop];
2571
+ if (value && /^[#\w\s,'"().%-]+$/.test(value)) parts.push(`${prop}: ${value}`);
2572
+ }
2573
+ return parts.join("; ");
2574
+ };
2575
+ const flatStyles = (items) => items.flatMap((item) => item.items ? flatStyles(item.items) : [item]);
2576
+ const styleFormats = () => {
2577
+ const custom = editor.options.styleFormats;
2578
+ if (!custom) return defaultStyleFormats();
2579
+ return editor.options.styleFormatsMerge ? [...defaultStyleFormats(), ...custom] : custom;
2580
+ };
2581
+ registry.addMenuButton("styles", {
2582
+ tooltip: t("styles"),
2583
+ minChars: 10,
2584
+ label: (e) => flatStyles(styleFormats()).find((item) => e.formatter.match(formatOf(item)))?.title ?? t("styles"),
2585
+ items: (e) => {
2586
+ const entries = [];
2587
+ const add = (items, prefix) => {
2588
+ items.forEach((item, index) => {
2589
+ if (item.items) {
2590
+ if (entries.length) entries.push({ type: "separator" });
2591
+ entries.push({ type: "heading", label: item.title });
2592
+ add(item.items, `${prefix}${index}-`);
2593
+ return;
2594
+ }
2595
+ entries.push({
2596
+ id: `style-${prefix}${index}`,
2597
+ label: item.title,
2598
+ labelStyle: previewStyle(item),
2599
+ active: e.formatter.match(formatOf(item)),
2600
+ // Формат по селектору без подходящих элементов (картинка не выделена) — неактивен.
2601
+ disabled: !e.formatter.canApply(formatOf(item)),
2602
+ onSelect: () => e.formatter.toggle(formatOf(item))
2603
+ });
2604
+ });
2605
+ };
2606
+ add(styleFormats(), "");
2607
+ return entries;
2608
+ }
2609
+ });
2712
2610
  const families = editor.options.fontFamilies ?? defaultFontFamilies;
2713
2611
  registry.addMenuButton("fontfamily", {
2714
2612
  tooltip: t("fontFamily"),
@@ -2874,7 +2772,7 @@ function registerBuiltins(editor) {
2874
2772
  tooltip: t("image"),
2875
2773
  onAction: (e) => openImageDialog(e)
2876
2774
  });
2877
- const imageAlign = () => getSelectedImage(state())?.node.attrs.align ?? null;
2775
+ const imageAlign = () => getSelectedImage(state())?.attrs.align ?? null;
2878
2776
  const imageAlignButton = (name, align, svg, label) => registry.addToggleButton(name, {
2879
2777
  icon: svg,
2880
2778
  tooltip: t(label),
@@ -2906,12 +2804,19 @@ function registerBuiltins(editor) {
2906
2804
  tooltip: t("image.editAlt"),
2907
2805
  onAction: (e) => openImageAltDialog(e)
2908
2806
  });
2807
+ registry.addToggleButton("imagecaption", {
2808
+ icon: icons.imageCaption,
2809
+ tooltip: t("image.caption"),
2810
+ isActive: (e) => hasImageCaption(e.view.state),
2811
+ onAction: (e) => e.exec(toggleImageCaption)
2812
+ });
2909
2813
  registry.addButton("imagedelete", {
2910
2814
  icon: icons.trash,
2911
2815
  tooltip: t("image.delete"),
2912
2816
  onAction: (e) => e.exec((s, dispatch) => {
2913
- if (!getSelectedImage(s)) return false;
2914
- dispatch?.(s.tr.deleteSelection().scrollIntoView());
2817
+ const image = getSelectedImage(s);
2818
+ if (!image) return false;
2819
+ dispatch?.(s.tr.delete(image.pos, image.pos + image.node.nodeSize).scrollIntoView());
2915
2820
  return true;
2916
2821
  })
2917
2822
  });
@@ -2948,7 +2853,13 @@ function registerBuiltins(editor) {
2948
2853
  registry.addContextToolbar("image", {
2949
2854
  label: t("image.toolbar"),
2950
2855
  predicate: (e) => !!getSelectedImage(e.view.state),
2951
- items: "imagealignleft imagealigncenter imagealignright | imagesize imagealt | imagedelete"
2856
+ items: "imagealignleft imagealigncenter imagealignright | imagesize imagealt imagecaption | imagedelete",
2857
+ // Над картинкой (и с подписью — над всей figure, даже когда курсор в подписи).
2858
+ anchor: (e) => {
2859
+ const image = getSelectedImage(e.view.state);
2860
+ const dom = image ? e.view.nodeDOM(image.pos) : null;
2861
+ return dom?.getBoundingClientRect() ?? null;
2862
+ }
2952
2863
  });
2953
2864
  }
2954
2865
 
@@ -2958,13 +2869,16 @@ var VIEWPORT_PADDING = 8;
2958
2869
  function positionFloating(floating, anchorRect, placement) {
2959
2870
  const vw = window.innerWidth;
2960
2871
  const vh = window.innerHeight;
2961
- const { width, height } = floating.getBoundingClientRect();
2872
+ const width = floating.offsetWidth;
2873
+ const height = floating.offsetHeight;
2962
2874
  const spaceBelow = vh - anchorRect.bottom;
2963
2875
  const spaceAbove = anchorRect.top;
2964
2876
  const preferTop = placement === "top-start";
2965
2877
  const placeTop = preferTop ? spaceAbove >= height + GAP || spaceAbove > spaceBelow : spaceBelow < height + GAP && spaceAbove > spaceBelow;
2966
2878
  let top = placeTop ? anchorRect.top - height - GAP : anchorRect.bottom + GAP;
2967
- let left = placement === "bottom-end" ? anchorRect.right - width : placement === "bottom" ? anchorRect.left + anchorRect.width / 2 - width / 2 : anchorRect.left;
2879
+ const rtl = isRtl(floating);
2880
+ const alignEnd = placement === "bottom-end" !== rtl;
2881
+ let left = placement === "bottom" ? anchorRect.left + anchorRect.width / 2 - width / 2 : alignEnd ? anchorRect.right - width : anchorRect.left;
2968
2882
  left = Math.max(VIEWPORT_PADDING, Math.min(left, vw - width - VIEWPORT_PADDING));
2969
2883
  top = Math.max(VIEWPORT_PADDING, Math.min(top, vh - height - VIEWPORT_PADDING));
2970
2884
  floating.style.left = `${Math.round(left)}px`;
@@ -2976,6 +2890,7 @@ var Popover = class {
2976
2890
  el;
2977
2891
  options;
2978
2892
  closed = false;
2893
+ unlisten = [];
2979
2894
  constructor(options) {
2980
2895
  this.options = options;
2981
2896
  this.el = document.createElement("div");
@@ -2983,8 +2898,10 @@ var Popover = class {
2983
2898
  this.el.append(options.content);
2984
2899
  options.host.append(this.el);
2985
2900
  this.reposition();
2986
- document.addEventListener("keydown", this.onKeyDown, true);
2987
- document.addEventListener("pointerdown", this.onPointerDown, true);
2901
+ this.unlisten = [
2902
+ listenDocument(this.el, "keydown", this.onKeyDown),
2903
+ listenDocument(this.el, "pointerdown", this.onPointerDown)
2904
+ ];
2988
2905
  openStack.push(this);
2989
2906
  window.addEventListener("resize", this.reposition);
2990
2907
  window.addEventListener("scroll", this.reposition, true);
@@ -3002,8 +2919,7 @@ var Popover = class {
3002
2919
  if (this.closed) return;
3003
2920
  this.closed = true;
3004
2921
  openStack.splice(openStack.indexOf(this), 1);
3005
- document.removeEventListener("keydown", this.onKeyDown, true);
3006
- document.removeEventListener("pointerdown", this.onPointerDown, true);
2922
+ this.unlisten.forEach((stop) => stop());
3007
2923
  window.removeEventListener("resize", this.reposition);
3008
2924
  window.removeEventListener("scroll", this.reposition, true);
3009
2925
  this.el.remove();
@@ -3011,18 +2927,17 @@ var Popover = class {
3011
2927
  }
3012
2928
  /** Был ли фокус внутри панели в момент закрытия (тогда его надо вернуть на кнопку). */
3013
2929
  focusWasInside = false;
3014
- onKeyDown = (event) => {
2930
+ onKeyDown = (event, target) => {
3015
2931
  if (event.key !== "Escape" || event.defaultPrevented) return;
3016
2932
  if (openStack[openStack.length - 1] !== this) return;
3017
- if (event.target?.closest?.(".nova-dialog")) return;
2933
+ if (target?.closest?.(".nova-dialog")) return;
3018
2934
  event.preventDefault();
3019
2935
  event.stopPropagation();
3020
- this.focusWasInside = this.el.contains(document.activeElement);
2936
+ this.focusWasInside = this.el.contains(activeElement(this.el));
3021
2937
  this.close("escape");
3022
2938
  };
3023
- onPointerDown = (event) => {
2939
+ onPointerDown = (_event, target) => {
3024
2940
  if (this.options.dismissOnOutside === false) return;
3025
- const target = event.target;
3026
2941
  if (this.el.contains(target)) return;
3027
2942
  if (this.options.ignore?.some((el) => el.contains(target))) return;
3028
2943
  this.close("outside");
@@ -3161,11 +3076,12 @@ function createToolbar(editor, host, config, mode, { warnUnknown = true } = {})
3161
3076
  "keydown",
3162
3077
  (event) => {
3163
3078
  const list = focusables();
3164
- const index = list.indexOf(document.activeElement);
3079
+ const index = list.indexOf(activeElement(host));
3165
3080
  if (index < 0) return;
3166
3081
  let next = null;
3167
- if (event.key === "ArrowRight") next = index + 1;
3168
- else if (event.key === "ArrowLeft") next = index - 1;
3082
+ const key3 = logicalKey(event, host);
3083
+ if (key3 === "ArrowRight") next = index + 1;
3084
+ else if (key3 === "ArrowLeft") next = index - 1;
3169
3085
  else if (event.key === "Home") next = 0;
3170
3086
  else if (event.key === "End") next = list.length - 1;
3171
3087
  else if (event.key === "Escape") {
@@ -3189,12 +3105,13 @@ function createToolbar(editor, host, config, mode, { warnUnknown = true } = {})
3189
3105
  const list = [...overflowBox.querySelectorAll("button")].filter(
3190
3106
  (b) => !b.disabled
3191
3107
  );
3192
- const index = list.indexOf(document.activeElement);
3108
+ const index = list.indexOf(activeElement(overflowBox));
3193
3109
  if (index < 0) return;
3194
- if (event.key === "ArrowRight" || event.key === "ArrowDown") {
3110
+ const key3 = logicalKey(event, overflowBox);
3111
+ if (key3 === "ArrowRight" || key3 === "ArrowDown") {
3195
3112
  event.preventDefault();
3196
3113
  list[(index + 1) % list.length].focus();
3197
- } else if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
3114
+ } else if (key3 === "ArrowLeft" || key3 === "ArrowUp") {
3198
3115
  event.preventDefault();
3199
3116
  list[(index - 1 + list.length) % list.length].focus();
3200
3117
  }
@@ -3294,7 +3211,14 @@ function renderControl(editor, name, spec) {
3294
3211
  el.classList.toggle("is-active", active);
3295
3212
  if (spec.type === "button") el.setAttribute("aria-pressed", String(active));
3296
3213
  }
3297
- if (label && spec.type === "menu") label.textContent = spec.label?.(editor) ?? spec.text ?? "";
3214
+ if (label && spec.type === "menu") {
3215
+ const text = spec.label?.(editor) ?? spec.text ?? "";
3216
+ label.textContent = text;
3217
+ el.setAttribute(
3218
+ "aria-label",
3219
+ text && text !== spec.tooltip ? `${text}, ${spec.tooltip}` : spec.tooltip ?? text
3220
+ );
3221
+ }
3298
3222
  if (colorBar && spec.type === "panel" && spec.indicator) {
3299
3223
  const color = spec.indicator(editor);
3300
3224
  colorBar.style.background = color ?? "";
@@ -3486,15 +3410,19 @@ var MARK_TAGS = {
3486
3410
  subscript: "sub",
3487
3411
  superscript: "sup"
3488
3412
  };
3413
+ var CJK = String.raw`\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}`;
3414
+ var LETTER = String.raw`(?:(?![${CJK}])[\p{L}\p{N}])`;
3415
+ var WORD = new RegExp(`[${CJK}]|${LETTER}+(?:['\u2019-]${LETTER}+)*`, "gu");
3489
3416
  function countWords(text) {
3490
- const matches = text.match(/[\p{L}\p{N}]+(?:['’-][\p{L}\p{N}]+)*/gu);
3491
- return matches ? matches.length : 0;
3417
+ return text.match(WORD)?.length ?? 0;
3492
3418
  }
3493
3419
  function createStatusbar(editor, host) {
3494
3420
  host.className = "nova-statusbar";
3495
3421
  const path = h("div", { className: "nova-path", "aria-hidden": "true" });
3496
3422
  const words = h("div", { className: "nova-wordcount", "aria-live": "off" });
3497
3423
  host.append(path, words);
3424
+ const resize = editor.options.resize;
3425
+ const removeHandle = resize ? createResizeHandle(editor, host, resize === "both") : null;
3498
3426
  let timer = null;
3499
3427
  const updateWords = () => {
3500
3428
  const doc = editor.view.state.doc;
@@ -3516,7 +3444,12 @@ function createStatusbar(editor, host) {
3516
3444
  const tag = MARK_TAGS[mark.type.name];
3517
3445
  if (tag) parts.push(tag);
3518
3446
  }
3519
- path.textContent = parts.join(" \u203A ");
3447
+ path.replaceChildren(
3448
+ ...parts.flatMap((tag, i) => [
3449
+ ...i ? [" \u203A "] : [],
3450
+ h("span", { className: "nova-path-item" }, tag)
3451
+ ])
3452
+ );
3520
3453
  if (docChanged) {
3521
3454
  if (timer) clearTimeout(timer);
3522
3455
  timer = setTimeout(updateWords, 250);
@@ -3528,17 +3461,237 @@ function createStatusbar(editor, host) {
3528
3461
  update,
3529
3462
  destroy: () => {
3530
3463
  if (timer) clearTimeout(timer);
3464
+ removeHandle?.();
3531
3465
  host.replaceChildren();
3532
3466
  }
3533
3467
  };
3534
3468
  }
3469
+ var MIN_HEIGHT = 100;
3470
+ var MIN_WIDTH = 200;
3471
+ var KEY_STEP = 20;
3472
+ function createResizeHandle(editor, host, both) {
3473
+ const root = editor.root;
3474
+ const handle = h("div", {
3475
+ className: "nova-resize-handle",
3476
+ role: "separator",
3477
+ tabIndex: 0,
3478
+ "aria-orientation": "horizontal",
3479
+ "aria-label": editor.ui.t("status.resize")
3480
+ });
3481
+ handle.append(icon(both ? icons.resizeHandleBoth : icons.resizeHandle));
3482
+ root.dataset.resize = both ? "both" : "vertical";
3483
+ host.append(handle);
3484
+ const setSize = (height, width) => {
3485
+ root.style.boxSizing = "border-box";
3486
+ root.style.height = `${Math.max(MIN_HEIGHT, Math.round(height))}px`;
3487
+ if (both && width !== void 0) {
3488
+ const max = root.parentElement?.clientWidth || Infinity;
3489
+ root.style.width = `${Math.min(max, Math.max(MIN_WIDTH, Math.round(width)))}px`;
3490
+ }
3491
+ handle.setAttribute("aria-valuenow", String(root.offsetHeight));
3492
+ };
3493
+ let start = null;
3494
+ const onDown = (event) => {
3495
+ if (editor.isDisabled()) return;
3496
+ event.preventDefault();
3497
+ handle.setPointerCapture(event.pointerId);
3498
+ start = {
3499
+ x: event.clientX,
3500
+ y: event.clientY,
3501
+ height: root.offsetHeight,
3502
+ width: root.offsetWidth
3503
+ };
3504
+ };
3505
+ const onMove = (event) => {
3506
+ if (!start) return;
3507
+ const dx = (event.clientX - start.x) * (isRtl(root) ? -1 : 1);
3508
+ setSize(start.height + event.clientY - start.y, start.width + dx);
3509
+ };
3510
+ const onUp = (event) => {
3511
+ if (!start) return;
3512
+ start = null;
3513
+ if (handle.hasPointerCapture(event.pointerId)) handle.releasePointerCapture(event.pointerId);
3514
+ };
3515
+ const onKey = (event) => {
3516
+ const dy = event.key === "ArrowDown" ? KEY_STEP : event.key === "ArrowUp" ? -KEY_STEP : 0;
3517
+ const key3 = logicalKey(event, root);
3518
+ const dx = both ? key3 === "ArrowRight" ? KEY_STEP : key3 === "ArrowLeft" ? -KEY_STEP : 0 : 0;
3519
+ if (!dx && !dy) return;
3520
+ event.preventDefault();
3521
+ setSize(root.offsetHeight + dy, root.offsetWidth + dx);
3522
+ };
3523
+ handle.addEventListener("pointerdown", onDown);
3524
+ handle.addEventListener("pointermove", onMove);
3525
+ handle.addEventListener("pointerup", onUp);
3526
+ handle.addEventListener("pointercancel", onUp);
3527
+ handle.addEventListener("keydown", onKey);
3528
+ return () => {
3529
+ handle.remove();
3530
+ delete root.dataset.resize;
3531
+ };
3532
+ }
3533
+
3534
+ // src/content-css.ts
3535
+ var GLOBAL_AT_RULES = /^@(font-face|(-webkit-)?keyframes|property|counter-style|page|font-feature-values|font-palette-values)\b/i;
3536
+ var GROUP_AT_RULES = /^@(media|supports|container|layer|document|scope)\b/i;
3537
+ function splitTopLevel(css) {
3538
+ const items = [];
3539
+ let i = 0;
3540
+ let start = 0;
3541
+ let depth = 0;
3542
+ let prelude = "";
3543
+ while (i < css.length) {
3544
+ const ch = css[i];
3545
+ if (ch === "/" && css[i + 1] === "*") {
3546
+ const end = css.indexOf("*/", i + 2);
3547
+ const cut = end === -1 ? css.length : end + 2;
3548
+ if (depth === 0) {
3549
+ css = css.slice(0, i) + css.slice(cut);
3550
+ continue;
3551
+ }
3552
+ i = cut;
3553
+ continue;
3554
+ }
3555
+ if (ch === '"' || ch === "'") {
3556
+ i++;
3557
+ while (i < css.length && css[i] !== ch) i += css[i] === "\\" ? 2 : 1;
3558
+ i++;
3559
+ continue;
3560
+ }
3561
+ if (ch === "{") {
3562
+ if (depth === 0) {
3563
+ prelude = css.slice(start, i).trim();
3564
+ start = i + 1;
3565
+ }
3566
+ depth++;
3567
+ } else if (ch === "}") {
3568
+ depth--;
3569
+ if (depth === 0) {
3570
+ items.push({ prelude, body: css.slice(start, i) });
3571
+ start = i + 1;
3572
+ }
3573
+ if (depth < 0) depth = 0;
3574
+ } else if (ch === ";" && depth === 0) {
3575
+ const statement = css.slice(start, i).trim();
3576
+ if (statement) items.push({ prelude: statement, body: null });
3577
+ start = i + 1;
3578
+ }
3579
+ i++;
3580
+ }
3581
+ return items;
3582
+ }
3583
+ function splitSelectors(list) {
3584
+ const parts = [];
3585
+ let depth = 0;
3586
+ let quote = "";
3587
+ let start = 0;
3588
+ for (let i = 0; i < list.length; i++) {
3589
+ const ch = list[i];
3590
+ if (quote) {
3591
+ if (ch === "\\") i++;
3592
+ else if (ch === quote) quote = "";
3593
+ } else if (ch === '"' || ch === "'") quote = ch;
3594
+ else if (ch === "(" || ch === "[") depth++;
3595
+ else if (ch === ")" || ch === "]") depth--;
3596
+ else if (ch === "," && depth === 0) {
3597
+ parts.push(list.slice(start, i));
3598
+ start = i + 1;
3599
+ }
3600
+ }
3601
+ parts.push(list.slice(start));
3602
+ return parts.map((s) => s.trim()).filter(Boolean);
3603
+ }
3604
+ function scopeSelector(selector, scope) {
3605
+ let rest = selector;
3606
+ let root = false;
3607
+ for (; ; ) {
3608
+ const m = rest.match(/^(html|body|:root)(?![\w-])\s*/i);
3609
+ if (!m) break;
3610
+ root = true;
3611
+ rest = rest.slice(m[0].length);
3612
+ }
3613
+ if (!root) return `${scope} ${selector}`;
3614
+ if (/^[.#[:]/.test(rest)) {
3615
+ const end = rest.search(/[\s>+~]/);
3616
+ return end === -1 ? `${scope}${rest}` : `${scope}${rest.slice(0, end)} ${rest.slice(end).trim()}`;
3617
+ }
3618
+ return rest ? `${scope} ${rest}` : scope;
3619
+ }
3620
+ function scopeCss(css, scope) {
3621
+ const out = [];
3622
+ for (const { prelude, body } of splitTopLevel(css)) {
3623
+ if (body === null) {
3624
+ if (/^@layer\b/i.test(prelude)) out.push(`${prelude};`);
3625
+ continue;
3626
+ }
3627
+ if (GLOBAL_AT_RULES.test(prelude)) out.push(`${prelude}{${body}}`);
3628
+ else if (GROUP_AT_RULES.test(prelude)) out.push(`${prelude}{${scopeCss(body, scope)}}`);
3629
+ else if (prelude.startsWith("@"))
3630
+ continue;
3631
+ else {
3632
+ const selectors = splitSelectors(prelude).map((s) => scopeSelector(s, scope));
3633
+ if (selectors.length) out.push(`${selectors.join(", ")}{${body}}`);
3634
+ }
3635
+ }
3636
+ return out.join("\n");
3637
+ }
3638
+ function absolutizeUrls(css, base) {
3639
+ return css.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi, (match, quote, url) => {
3640
+ if (/^(data:|https?:|\/\/|#)/i.test(url)) return match;
3641
+ try {
3642
+ return `url(${quote}${new URL(url, base).href}${quote})`;
3643
+ } catch {
3644
+ return match;
3645
+ }
3646
+ });
3647
+ }
3648
+ var IMPORT = /@import\s+(?:url\(\s*)?(['"]?)([^'")\s;]+)\1\s*\)?([^;]*);/gi;
3649
+ async function loadCss(url, depth = 0) {
3650
+ const base = new URL(url, document.baseURI).href;
3651
+ const response = await fetch(base);
3652
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
3653
+ let css = absolutizeUrls(await response.text(), base);
3654
+ if (depth >= 3) return css.replace(IMPORT, "");
3655
+ const imports = [...css.matchAll(IMPORT)];
3656
+ for (const m of imports) {
3657
+ const media = m[3].trim();
3658
+ let inner = "";
3659
+ try {
3660
+ inner = await loadCss(new URL(m[2], base).href, depth + 1);
3661
+ } catch (error) {
3662
+ console.warn(`[nova] contentCss: could not load ${m[2]}`, error);
3663
+ }
3664
+ css = css.replace(m[0], media ? `@media ${media}{${inner}}` : inner);
3665
+ }
3666
+ return css;
3667
+ }
3668
+ function attachCss(host, css) {
3669
+ const root = host.getRootNode();
3670
+ const canAdopt = "adoptedStyleSheets" in root && typeof CSSStyleSheet !== "undefined" && "replaceSync" in CSSStyleSheet.prototype;
3671
+ if (canAdopt) {
3672
+ try {
3673
+ const sheet = new CSSStyleSheet();
3674
+ sheet.replaceSync(css);
3675
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
3676
+ return () => {
3677
+ root.adoptedStyleSheets = root.adoptedStyleSheets.filter((s) => s !== sheet);
3678
+ };
3679
+ } catch {
3680
+ }
3681
+ }
3682
+ const style = document.createElement("style");
3683
+ style.setAttribute("data-nova-content-css", "");
3684
+ style.textContent = css;
3685
+ host.prepend(style);
3686
+ return () => style.remove();
3687
+ }
3535
3688
 
3536
3689
  // src/editor.ts
3537
3690
  import { dropCursor } from "prosemirror-dropcursor";
3538
3691
  import { gapCursor } from "prosemirror-gapcursor";
3539
3692
  import { history } from "prosemirror-history";
3540
3693
  import { keymap as keymap2 } from "prosemirror-keymap";
3541
- import { Node as PMNode } from "prosemirror-model";
3694
+ import { Node as PMNode, Slice as Slice2 } from "prosemirror-model";
3542
3695
  import { EditorState } from "prosemirror-state";
3543
3696
  import { EditorView } from "prosemirror-view";
3544
3697
 
@@ -3609,14 +3762,65 @@ function buildKeymap(resolve = (name) => commands[name]) {
3609
3762
  "Mod-Shift-j": commands.alignJustify,
3610
3763
  "Mod-\\": commands.clearFormatting,
3611
3764
  "Shift-Enter": insertHardBreak,
3612
- Enter: (state, dispatch) => splitListItem(nodesOf(state).list_item)(state, dispatch),
3613
- Tab: commands.indent,
3614
- "Shift-Tab": commands.outdent
3765
+ Enter: chainCommands(
3766
+ exitImageCaption,
3767
+ (state, dispatch) => splitListItem(nodesOf(state).list_item)(state, dispatch)
3768
+ ),
3769
+ // Tab — только для списков (в абзаце остаётся переходом фокуса). Отступ абзаца — Mod-] / Mod-[.
3770
+ Tab: listIndent,
3771
+ "Shift-Tab": listOutdent,
3772
+ "Mod-]": commands.indent,
3773
+ "Mod-[": commands.outdent
3615
3774
  };
3616
3775
  if (!mac) keys["Mod-y"] = byName(resolve, "redo");
3617
3776
  return [keymap(keys), keymap(baseKeymap)];
3618
3777
  }
3619
3778
 
3779
+ // src/plugin-views.ts
3780
+ var reconfiguring = /* @__PURE__ */ new WeakSet();
3781
+ var kept = /* @__PURE__ */ new WeakMap();
3782
+ var wrapped = /* @__PURE__ */ new WeakSet();
3783
+ function keepPluginViews(plugins) {
3784
+ for (const plugin of plugins) {
3785
+ const spec = plugin.spec;
3786
+ const create = spec.view;
3787
+ if (!create || wrapped.has(plugin)) continue;
3788
+ wrapped.add(plugin);
3789
+ spec.view = (view) => {
3790
+ let views = kept.get(view);
3791
+ if (!views) kept.set(view, views = /* @__PURE__ */ new Map());
3792
+ let inner = views.get(plugin);
3793
+ if (!inner) views.set(plugin, inner = create(view));
3794
+ const current = inner;
3795
+ return {
3796
+ update: (v, prev) => current.update?.(v, prev),
3797
+ destroy: () => {
3798
+ if (reconfiguring.has(view)) return;
3799
+ views.delete(plugin);
3800
+ current.destroy?.();
3801
+ }
3802
+ };
3803
+ };
3804
+ }
3805
+ }
3806
+ function reconfigurePlugins(view, plugins) {
3807
+ keepPluginViews(plugins);
3808
+ reconfiguring.add(view);
3809
+ try {
3810
+ view.updateState(view.state.reconfigure({ plugins }));
3811
+ } finally {
3812
+ reconfiguring.delete(view);
3813
+ }
3814
+ const views = kept.get(view);
3815
+ if (!views) return;
3816
+ for (const [plugin, inner] of views) {
3817
+ if (!plugins.includes(plugin)) {
3818
+ views.delete(plugin);
3819
+ inner.destroy?.();
3820
+ }
3821
+ }
3822
+ }
3823
+
3620
3824
  // src/ui/search-bar.ts
3621
3825
  function createSearchBar(editor, before) {
3622
3826
  const { t } = editor.ui;
@@ -3854,7 +4058,7 @@ function linkBubblePlugin(editor) {
3854
4058
  const update = () => {
3855
4059
  const state = view.state;
3856
4060
  const link = getLinkAt(state);
3857
- const focused = view.hasFocus() || el.contains(document.activeElement);
4061
+ const focused = view.hasFocus() || el.contains(activeElement(el));
3858
4062
  if (!link || !focused || !editor.isEditable() || editor.ui.activeDialog || !state.selection.empty) {
3859
4063
  hide();
3860
4064
  return;
@@ -3895,7 +4099,7 @@ function linkBubblePlugin(editor) {
3895
4099
  }
3896
4100
 
3897
4101
  // src/ui/context-toolbar.ts
3898
- import { NodeSelection, Plugin as Plugin5, PluginKey as PluginKey5 } from "prosemirror-state";
4102
+ import { NodeSelection as NodeSelection2, Plugin as Plugin5, PluginKey as PluginKey5 } from "prosemirror-state";
3899
4103
  function contextToolbarPlugin(editor) {
3900
4104
  return new Plugin5({
3901
4105
  key: new PluginKey5("nova-context-toolbar"),
@@ -3934,7 +4138,7 @@ function contextToolbarPlugin(editor) {
3934
4138
  };
3935
4139
  const anchorRect = (spec) => {
3936
4140
  const { selection } = view.state;
3937
- if ((spec.position ?? "node") === "node" && selection instanceof NodeSelection) {
4141
+ if ((spec.position ?? "node") === "node" && selection instanceof NodeSelection2) {
3938
4142
  const dom = view.nodeDOM(selection.from);
3939
4143
  return dom?.getBoundingClientRect() ?? null;
3940
4144
  }
@@ -3957,10 +4161,10 @@ function contextToolbarPlugin(editor) {
3957
4161
  setTimeout(() => update(view), 0);
3958
4162
  };
3959
4163
  view.dom.addEventListener("pointerdown", onPointerDown);
3960
- document.addEventListener("pointerup", onPointerUp);
4164
+ const stopPointerUp = listenDocument(container, "pointerup", onPointerUp);
3961
4165
  const coarse = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
3962
4166
  const update = (v) => {
3963
- const focused = v.hasFocus() || container.contains(document.activeElement);
4167
+ const focused = v.hasFocus() || container.contains(activeElement(container));
3964
4168
  if (!focused || !editor.isEditable() || editor.ui.activeDialog || dragging) return hide();
3965
4169
  const match = editor.ui.registry.getContextToolbars().find(([, spec2]) => spec2.predicate(editor));
3966
4170
  if (!match) return hide();
@@ -3984,13 +4188,13 @@ function contextToolbarPlugin(editor) {
3984
4188
  });
3985
4189
  container.addEventListener("keydown", (event) => {
3986
4190
  const buttons = [...container.querySelectorAll("button:not(:disabled)")];
3987
- const index = buttons.indexOf(document.activeElement);
4191
+ const index = buttons.indexOf(activeElement(container));
3988
4192
  if (event.key === "Escape") {
3989
4193
  event.preventDefault();
3990
4194
  editor.focus();
3991
4195
  } else if (index >= 0 && (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
3992
4196
  event.preventDefault();
3993
- const step = event.key === "ArrowRight" ? 1 : -1;
4197
+ const step = logicalKey(event, container) === "ArrowRight" ? 1 : -1;
3994
4198
  buttons[(index + step + buttons.length) % buttons.length].focus();
3995
4199
  }
3996
4200
  });
@@ -4014,7 +4218,7 @@ function contextToolbarPlugin(editor) {
4014
4218
  destroy() {
4015
4219
  view.dom.removeEventListener("blur", onBlur);
4016
4220
  view.dom.removeEventListener("pointerdown", onPointerDown);
4017
- document.removeEventListener("pointerup", onPointerUp);
4221
+ stopPointerUp();
4018
4222
  window.removeEventListener("scroll", reposition, true);
4019
4223
  window.removeEventListener("resize", reposition);
4020
4224
  container.remove();
@@ -4032,8 +4236,8 @@ function focusContextToolbar(editor) {
4032
4236
  }
4033
4237
 
4034
4238
  // src/ui/image-view.ts
4035
- import { NodeSelection as NodeSelection2 } from "prosemirror-state";
4036
- var MIN_WIDTH = 24;
4239
+ import { NodeSelection as NodeSelection3 } from "prosemirror-state";
4240
+ var MIN_WIDTH2 = 24;
4037
4241
  var ImageView = class {
4038
4242
  constructor(node, view, getPos, editor) {
4039
4243
  this.view = view;
@@ -4067,6 +4271,7 @@ var ImageView = class {
4067
4271
  if (this.img.getAttribute("src") !== safeSrc) this.img.setAttribute("src", safeSrc);
4068
4272
  this.setAttr("alt", alt);
4069
4273
  this.setAttr("title", title);
4274
+ this.setAttr("class", classAttr(this.node.attrs.class).class ?? null);
4070
4275
  const w = imageSize(width);
4071
4276
  const h2 = imageSize(height);
4072
4277
  this.img.style.width = w ? `${w}px` : "";
@@ -4106,14 +4311,14 @@ var ImageView = class {
4106
4311
  const startX = event.clientX;
4107
4312
  const startWidth = rect.width;
4108
4313
  const ratio = rect.width > 0 ? rect.height / rect.width : this.img.naturalHeight / (this.img.naturalWidth || 1);
4109
- const maxWidth = Math.max(MIN_WIDTH, this.view.dom.clientWidth - 40);
4314
+ const maxWidth = Math.max(MIN_WIDTH2, this.view.dom.clientWidth - 40);
4110
4315
  const direction = corner === "ne" || corner === "se" ? 1 : -1;
4111
4316
  let width = startWidth;
4112
4317
  this.resizing = true;
4113
4318
  this.dom.classList.add("is-resizing");
4114
4319
  const onMove = (e) => {
4115
4320
  width = Math.round(
4116
- Math.min(maxWidth, Math.max(MIN_WIDTH, startWidth + direction * (e.clientX - startX)))
4321
+ Math.min(maxWidth, Math.max(MIN_WIDTH2, startWidth + direction * (e.clientX - startX)))
4117
4322
  );
4118
4323
  this.img.style.width = `${width}px`;
4119
4324
  this.dom.dataset.size = `${width} \xD7 ${Math.round(width * ratio)}`;
@@ -4132,7 +4337,7 @@ var ImageView = class {
4132
4337
  width,
4133
4338
  height: Math.round(width * ratio)
4134
4339
  });
4135
- tr.setSelection(NodeSelection2.create(tr.doc, pos));
4340
+ tr.setSelection(NodeSelection3.create(tr.doc, pos));
4136
4341
  this.view.dispatch(tr);
4137
4342
  };
4138
4343
  handle.addEventListener("pointermove", onMove);
@@ -4186,7 +4391,7 @@ function autocompleterPlugin(editor) {
4186
4391
  items = [];
4187
4392
  view.dom.removeAttribute("aria-activedescendant");
4188
4393
  view.dom.removeAttribute("aria-controls");
4189
- view.dom.setAttribute("aria-expanded", "false");
4394
+ view.dom.removeAttribute("aria-expanded");
4190
4395
  };
4191
4396
  const select = (view, index) => {
4192
4397
  const item = items[index];
@@ -4228,7 +4433,6 @@ function autocompleterPlugin(editor) {
4228
4433
  });
4229
4434
  list.hidden = false;
4230
4435
  view.dom.setAttribute("aria-controls", listId);
4231
- view.dom.setAttribute("aria-expanded", "true");
4232
4436
  setActive(view, Math.min(active, Math.max(0, items.length - 1)));
4233
4437
  const coords = view.coordsAtPos(match.from);
4234
4438
  positionFloating(
@@ -4331,6 +4535,9 @@ var Notifications = class {
4331
4535
  { type: "button", className: "nova-btn", "aria-label": this.closeLabel },
4332
4536
  icon(icons.close)
4333
4537
  );
4538
+ const actions = (options.actions ?? []).map(
4539
+ (action) => h("button", { type: "button", className: "nova-btn nova-notification-action" }, action.label)
4540
+ );
4334
4541
  const el = h(
4335
4542
  "div",
4336
4543
  {
@@ -4338,16 +4545,32 @@ var Notifications = class {
4338
4545
  role: type === "error" ? "alert" : "status"
4339
4546
  },
4340
4547
  text,
4548
+ ...actions,
4341
4549
  closeBtn
4342
4550
  );
4343
4551
  this.region.append(el);
4344
4552
  let timer = null;
4553
+ let closed = false;
4345
4554
  const close = () => {
4555
+ if (closed) return;
4556
+ closed = true;
4346
4557
  if (timer) clearTimeout(timer);
4347
4558
  el.remove();
4348
4559
  };
4349
- closeBtn.addEventListener("click", close);
4350
- if (timeout > 0) timer = setTimeout(close, timeout);
4560
+ const dismiss = () => {
4561
+ if (closed) return;
4562
+ close();
4563
+ options.onClose?.();
4564
+ };
4565
+ actions.forEach(
4566
+ (button, i) => button.addEventListener("click", () => {
4567
+ close();
4568
+ options.actions[i].onAction();
4569
+ })
4570
+ );
4571
+ closeBtn.addEventListener("click", dismiss);
4572
+ if (timeout > 0) timer = setTimeout(dismiss, timeout);
4573
+ actions[0]?.focus({ preventScroll: true });
4351
4574
  return { close, setText: (value) => text.textContent = value };
4352
4575
  }
4353
4576
  destroy() {
@@ -4356,6 +4579,7 @@ var Notifications = class {
4356
4579
  };
4357
4580
 
4358
4581
  // src/ui/registry.ts
4582
+ var sidebarIcon = icons.sidebar;
4359
4583
  var Registry = class {
4360
4584
  controls = /* @__PURE__ */ new Map();
4361
4585
  addButton(name, spec) {
@@ -4404,6 +4628,24 @@ var Registry = class {
4404
4628
  contextToolbars = /* @__PURE__ */ new Map();
4405
4629
  autocompleters = /* @__PURE__ */ new Map();
4406
4630
  /** Автокомплитер по символу-триггеру: '/' — команды, '@' — упоминания, ':' — эмодзи. */
4631
+ sidebars = /* @__PURE__ */ new Map();
4632
+ /**
4633
+ * Боковая панель (показ — editor.ui.sidebar). Если имя свободно, добавляется и кнопка-переключатель
4634
+ * с этим именем для тулбара и меню (`button: false` — без неё).
4635
+ */
4636
+ addSidebar(name, spec) {
4637
+ this.sidebars.set(name, spec);
4638
+ if (spec.button === false || this.has(name)) return;
4639
+ this.addToggleButton(name, {
4640
+ tooltip: spec.tooltip ?? spec.title,
4641
+ icon: spec.icon ?? sidebarIcon,
4642
+ isActive: (editor) => editor.ui.sidebar.isOpen(name),
4643
+ onAction: (editor) => void editor.ui.sidebar.toggle(name)
4644
+ });
4645
+ }
4646
+ getSidebar(name) {
4647
+ return this.sidebars.get(name);
4648
+ }
4407
4649
  addAutocompleter(name, spec) {
4408
4650
  this.autocompleters.set(name.toLowerCase(), spec);
4409
4651
  }
@@ -4428,6 +4670,148 @@ var Registry = class {
4428
4670
  }
4429
4671
  };
4430
4672
 
4673
+ // src/ui/sidebar.ts
4674
+ var Sidebars = class {
4675
+ constructor(editor) {
4676
+ this.editor = editor;
4677
+ }
4678
+ editor;
4679
+ current = null;
4680
+ mounted = /* @__PURE__ */ new Map();
4681
+ column = null;
4682
+ opening = Promise.resolve();
4683
+ destroyed = false;
4684
+ /** Имя открытой панели или null. */
4685
+ get active() {
4686
+ return this.current;
4687
+ }
4688
+ isOpen(name) {
4689
+ return this.current === name;
4690
+ }
4691
+ /**
4692
+ * Показать панель (другая открытая закрывается). \`focus\` — перевести фокус в панель
4693
+ * (например, когда её открыли с клавиатуры, чтобы сразу работать с ней).
4694
+ */
4695
+ async show(name, options = {}) {
4696
+ const spec = this.editor.ui.registry.getSidebar(name);
4697
+ if (!spec) {
4698
+ console.warn(`[nova] sidebar "${name}" is not registered`);
4699
+ return;
4700
+ }
4701
+ if (this.current !== name) {
4702
+ this.hide({ restoreFocus: false });
4703
+ this.editor.ui.closeOverlays();
4704
+ this.current = name;
4705
+ const mounted = this.mount(name, spec);
4706
+ this.opening = mounted.ready.then((ok) => {
4707
+ if (!ok || this.current !== name || this.destroyed) {
4708
+ if (this.current === name) this.current = null;
4709
+ return;
4710
+ }
4711
+ mounted.el.hidden = false;
4712
+ this.editor.root.classList.add("nova-sidebar-open");
4713
+ spec.onShow?.(this.editor);
4714
+ this.editor.updateUI();
4715
+ });
4716
+ }
4717
+ await this.opening;
4718
+ if (options.focus && this.current === name) {
4719
+ const el = this.mounted.get(name).el;
4720
+ (el.querySelector(FOCUSABLE) ?? el).focus();
4721
+ }
4722
+ }
4723
+ /** Закрыть открытую панель. Фокус из неё возвращается в текст. */
4724
+ hide(options = {}) {
4725
+ const name = this.current;
4726
+ if (!name) return;
4727
+ this.current = null;
4728
+ const mounted = this.mounted.get(name);
4729
+ if (!mounted) return;
4730
+ const hadFocus = mounted.el.contains(activeElement(mounted.el));
4731
+ mounted.el.hidden = true;
4732
+ this.editor.root.classList.remove("nova-sidebar-open");
4733
+ this.editor.ui.registry.getSidebar(name)?.onHide?.(this.editor);
4734
+ this.editor.updateUI();
4735
+ if (hadFocus && options.restoreFocus !== false) this.editor.focus();
4736
+ }
4737
+ toggle(name, options = {}) {
4738
+ if (this.current === name) {
4739
+ this.hide();
4740
+ return Promise.resolve();
4741
+ }
4742
+ return this.show(name, options);
4743
+ }
4744
+ destroy() {
4745
+ this.destroyed = true;
4746
+ this.mounted.forEach((mounted) => mounted.cleanup?.());
4747
+ this.mounted.clear();
4748
+ }
4749
+ /** Колонка «текст + панель»: создаётся при первой панели, без панелей разметка не меняется. */
4750
+ host() {
4751
+ if (this.column) return this.column;
4752
+ const content = this.editor.view.dom.parentElement;
4753
+ const column = h("div", { className: "nova-body" });
4754
+ content.before(column);
4755
+ column.append(content);
4756
+ this.column = column;
4757
+ return column;
4758
+ }
4759
+ mount(name, spec) {
4760
+ const existing = this.mounted.get(name);
4761
+ if (existing) return existing;
4762
+ const titleId = uniqueId("nova-sidebar-title");
4763
+ const body = h("div", { className: "nova-sidebar-body" });
4764
+ const close = h(
4765
+ "button",
4766
+ {
4767
+ type: "button",
4768
+ className: "nova-btn nova-sidebar-close",
4769
+ "aria-label": this.editor.ui.t("dialog.close"),
4770
+ onClick: () => this.hide()
4771
+ },
4772
+ icon(icons.close)
4773
+ );
4774
+ const header = spec.header === false ? null : h(
4775
+ "div",
4776
+ { className: "nova-sidebar-head" },
4777
+ h("h2", { id: titleId, className: "nova-sidebar-title" }, spec.title),
4778
+ close
4779
+ );
4780
+ const el = h(
4781
+ "div",
4782
+ {
4783
+ className: `nova-sidebar${header ? "" : " nova-sidebar-bare"}`,
4784
+ hidden: true,
4785
+ "data-sidebar": name,
4786
+ ...header ? { role: "complementary", "aria-labelledby": titleId } : {},
4787
+ onKeydown: ((event) => {
4788
+ if (event.key !== "Escape" || event.defaultPrevented) return;
4789
+ event.preventDefault();
4790
+ this.hide();
4791
+ })
4792
+ },
4793
+ header,
4794
+ body
4795
+ );
4796
+ this.host().append(el);
4797
+ const mounted = { el, ready: Promise.resolve(false) };
4798
+ mounted.ready = (async () => {
4799
+ try {
4800
+ const cleanup = await spec.render(body, this.editor);
4801
+ if (typeof cleanup === "function") mounted.cleanup = cleanup;
4802
+ return true;
4803
+ } catch (error) {
4804
+ console.error(`[nova] sidebar "${name}" failed to render`, error);
4805
+ el.remove();
4806
+ this.mounted.delete(name);
4807
+ return false;
4808
+ }
4809
+ })();
4810
+ this.mounted.set(name, mounted);
4811
+ return mounted;
4812
+ }
4813
+ };
4814
+
4431
4815
  // src/ui/tooltip.ts
4432
4816
  var SHOW_DELAY = 450;
4433
4817
  var Tooltip = class {
@@ -4485,13 +4869,14 @@ var Tooltip = class {
4485
4869
 
4486
4870
  // src/ui/manager.ts
4487
4871
  var UiManager = class {
4488
- constructor(root, t, focusEditor) {
4872
+ constructor(root, t, focusEditor, editor) {
4489
4873
  this.focusEditor = focusEditor;
4490
4874
  this.t = t;
4491
4875
  this.overlayHost = h("div", { className: "nova-overlays" });
4492
4876
  root.append(this.overlayHost);
4493
4877
  this.tooltip = new Tooltip(this.overlayHost);
4494
4878
  this.notifications = new Notifications(root, t("dialog.close"));
4879
+ this.sidebar = new Sidebars(editor);
4495
4880
  }
4496
4881
  focusEditor;
4497
4882
  registry = new Registry();
@@ -4499,9 +4884,19 @@ var UiManager = class {
4499
4884
  /** Слой для всех плавающих элементов. Лежит внутри .nova-editor, поэтому наследует тему. */
4500
4885
  overlayHost;
4501
4886
  tooltip;
4887
+ /** Боковые панели плагинов: show / hide / toggle (регистрация — registry.addSidebar). */
4888
+ sidebar;
4502
4889
  notifications;
4503
4890
  popover = null;
4504
- dialog = null;
4891
+ currentDialog = null;
4892
+ /**
4893
+ * Диалог по описанию полей (для плагинов): проверка, ошибки у полей, доступность.
4894
+ * Возвращает данные или null, если диалог закрыли. Реализация грузится при первом открытии.
4895
+ */
4896
+ async dialog(spec) {
4897
+ const { openFormDialog } = await import("./form-dialog-QH6KAERD.js");
4898
+ return openFormDialog(spec, this.t, (options) => this.openDialog(options));
4899
+ }
4505
4900
  /** Открыть поповер; одновременно открыт только один (кроме панели переполнения тулбара). */
4506
4901
  openPopover(options) {
4507
4902
  this.closePopover();
@@ -4544,7 +4939,7 @@ var UiManager = class {
4544
4939
  openDialog(options) {
4545
4940
  this.closePopover();
4546
4941
  this.dialogListeners.forEach((listener) => listener());
4547
- this.dialog?.close();
4942
+ this.currentDialog?.close();
4548
4943
  const handle = openDialog({
4549
4944
  cancelLabel: this.t("dialog.cancel"),
4550
4945
  closeLabel: this.t("dialog.close"),
@@ -4552,22 +4947,23 @@ var UiManager = class {
4552
4947
  host: this.overlayHost,
4553
4948
  returnFocus: this.focusEditor,
4554
4949
  onClose: () => {
4555
- if (this.dialog === handle) this.dialog = null;
4950
+ if (this.currentDialog === handle) this.currentDialog = null;
4556
4951
  options.onClose?.();
4557
4952
  }
4558
4953
  });
4559
- this.dialog = handle;
4954
+ this.currentDialog = handle;
4560
4955
  return handle;
4561
4956
  }
4562
4957
  get activeDialog() {
4563
- return this.dialog;
4958
+ return this.currentDialog;
4564
4959
  }
4565
4960
  notify(options) {
4566
4961
  return this.notifications.open(typeof options === "string" ? { text: options } : options);
4567
4962
  }
4568
4963
  destroy() {
4964
+ this.sidebar.destroy();
4569
4965
  this.closePopover();
4570
- this.dialog?.close();
4966
+ this.currentDialog?.close();
4571
4967
  this.tooltip.destroy();
4572
4968
  this.notifications.destroy();
4573
4969
  this.overlayHost.remove();
@@ -4575,7 +4971,17 @@ var UiManager = class {
4575
4971
  };
4576
4972
 
4577
4973
  // src/editor.ts
4974
+ var RTL_LANGUAGES = /* @__PURE__ */ new Set(["ar", "he", "iw", "fa", "ur", "ps", "sd", "ug", "yi", "dv", "ckb"]);
4975
+ function isRtlLanguage(language) {
4976
+ return !!language && RTL_LANGUAGES.has(language.toLowerCase().split(/[-_]/)[0]);
4977
+ }
4578
4978
  var htmlSerializer = new HTMLSerializer();
4979
+ var REMOTE_CHANGE_META = "nova:remote";
4980
+ var API_CHANGE_META = "nova:api";
4981
+ var INSERT_BLOCK_TAGS = new Set(
4982
+ "P H1 H2 H3 H4 H5 H6 UL OL TABLE BLOCKQUOTE PRE HR DIV FIGURE".split(" ")
4983
+ );
4984
+ var contentScopeId = 0;
4579
4985
  var Editor = class {
4580
4986
  view;
4581
4987
  root;
@@ -4588,6 +4994,8 @@ var Editor = class {
4588
4994
  toolbarHost;
4589
4995
  menubar;
4590
4996
  mode;
4997
+ /** Направление письма редактора (опция direction, язык или dir страницы). */
4998
+ direction;
4591
4999
  pluginsByName = /* @__PURE__ */ new Map();
4592
5000
  commandOverrides = /* @__PURE__ */ new Map();
4593
5001
  transactionTransforms = [];
@@ -4596,15 +5004,21 @@ var Editor = class {
4596
5004
  contentRules;
4597
5005
  /** Схема документа этого редактора: базовая + узлы и марки синхронных плагинов. */
4598
5006
  schema;
5007
+ /** Форматы: register / apply / remove / toggle / match. */
5008
+ formatter;
4599
5009
  statusbar;
4600
5010
  searchBar;
4601
5011
  destroyed = false;
4602
5012
  editable;
5013
+ disabled;
4603
5014
  pasteAsText;
4604
5015
  constructor(options) {
4605
5016
  this.options = options;
4606
5017
  this.root = document.createElement("div");
4607
5018
  this.root.className = "nova-editor";
5019
+ const direction = options.direction ?? (isRtlLanguage(options.language) ? "rtl" : void 0);
5020
+ if (direction) this.root.dir = direction;
5021
+ this.direction = direction ?? (options.element.closest("[dir]")?.getAttribute("dir") === "rtl" ? "rtl" : "ltr");
4608
5022
  options.element.appendChild(this.root);
4609
5023
  const toolbarHost = document.createElement("div");
4610
5024
  const contentHost = document.createElement("div");
@@ -4623,14 +5037,20 @@ var Editor = class {
4623
5037
  this.root.addEventListener("focusin", () => this.root.classList.add("is-focused"));
4624
5038
  this.root.addEventListener("focusout", () => {
4625
5039
  setTimeout(() => {
4626
- if (!this.root.contains(document.activeElement)) this.root.classList.remove("is-focused");
5040
+ if (!this.root.contains(activeElement(this.root)))
5041
+ this.root.classList.remove("is-focused");
4627
5042
  }, 0);
4628
5043
  });
4629
5044
  }
4630
5045
  this.ui = new UiManager(
4631
5046
  this.root,
4632
5047
  createTranslator(options.language, options.translations),
4633
- () => this.focus()
5048
+ () => this.focus(),
5049
+ this
5050
+ );
5051
+ this.root.style.setProperty(
5052
+ "--nova-caption-placeholder",
5053
+ JSON.stringify(this.ui.t("image.captionPlaceholder"))
4634
5054
  );
4635
5055
  const editorKeys = keymap2({
4636
5056
  "Mod-k": () => (openLinkDialog(this), true),
@@ -4666,39 +5086,60 @@ var Editor = class {
4666
5086
  const pluginPm = syncPlugins.flatMap((plugin) => this.collectPmPlugins(plugin));
4667
5087
  const hasRules = options.validElements !== void 0 || options.invalidElements !== void 0 || options.validStyles !== void 0;
4668
5088
  this.contentRules = hasRules ? new ContentRules(options) : null;
4669
- this.schema = this.buildSchema(syncPlugins);
5089
+ const allowedClasses = /* @__PURE__ */ new Set([
5090
+ ...formatClasses(Object.values(options.formats ?? {}).flat()),
5091
+ ...formatClasses(options.styleFormats ?? []),
5092
+ ...Array.isArray(options.validClasses) ? options.validClasses : [],
5093
+ ...[...options.tableClassList ?? [], ...options.tableCellClassList ?? []].flatMap(
5094
+ (o) => o.value.split(/\s+/).filter(Boolean)
5095
+ )
5096
+ ]);
5097
+ const htmlRules = htmlRulesFor(options);
5098
+ const allClasses = options.validClasses === true || options.validClasses === void 0 && !!htmlRules?.classOnBuiltIn;
5099
+ this.schema = this.buildSchema(
5100
+ syncPlugins,
5101
+ allClasses ? () => true : (name) => allowedClasses.has(name),
5102
+ htmlRules
5103
+ );
5104
+ this.formatter = new Formatter(this, allowedClasses);
5105
+ for (const [name, spec] of Object.entries(options.formats ?? {}))
5106
+ this.formatter.register(name, spec);
4670
5107
  syncPlugins.forEach((plugin) => this.registerCommands(plugin));
4671
5108
  const initialDoc = parseContent(this.schema, options.content ?? "");
5109
+ const tablesAnchor = searchPlugin();
5110
+ const initialPlugins = [
5111
+ // Первым: при открытом списке Enter/Tab/стрелки принадлежат автокомплитеру, а не раскладке клавиш.
5112
+ autocompleterPlugin(this),
5113
+ buildInputRules((name) => this.isAllowed(name), this.schema),
5114
+ editorKeys,
5115
+ // Сюда (до общей раскладки) встанут плагины таблиц после загрузки механики: Tab в таблице —
5116
+ // следующая ячейка, а не отступ списка. См. installTables().
5117
+ tablesAnchor,
5118
+ ...buildKeymap((name) => this.resolveCommand(name)),
5119
+ ...syncPlugins.some((plugin) => plugin.replaceHistory) ? [] : [history()],
5120
+ dropCursor({ color: "var(--nova-accent)", width: 2 }),
5121
+ gapCursor(),
5122
+ imageDropPastePlugin(this),
5123
+ embeddedImageUploadPlugin(this),
5124
+ pastePlugin(this),
5125
+ linkBubblePlugin(this),
5126
+ contextToolbarPlugin(this),
5127
+ ...this.contentRules ? [contentRulesPlugin(this.contentRules)] : [],
5128
+ ...pluginPm,
5129
+ ...options.prosemirrorPlugins ?? []
5130
+ ];
5131
+ keepPluginViews(initialPlugins);
4672
5132
  const state = EditorState.create({
4673
5133
  doc: this.contentRules ? this.contentRules.normalizeDoc(initialDoc) : initialDoc,
4674
- plugins: [
4675
- // Первым: при открытом списке Enter/Tab/стрелки принадлежат автокомплитеру, а не раскладке клавиш.
4676
- autocompleterPlugin(this),
4677
- buildInputRules((name) => this.isAllowed(name), this.schema),
4678
- editorKeys,
4679
- // Таблицы до общей раскладки: Tab в таблице — следующая ячейка, а не отступ списка.
4680
- ...tablePlugins(),
4681
- searchPlugin(),
4682
- ...buildKeymap((name) => this.resolveCommand(name)),
4683
- ...syncPlugins.some((plugin) => plugin.replaceHistory) ? [] : [history()],
4684
- dropCursor({ color: "var(--nova-accent)", width: 2 }),
4685
- gapCursor(),
4686
- imageDropPastePlugin(this),
4687
- embeddedImageUploadPlugin(this),
4688
- pastePlugin(this),
4689
- linkBubblePlugin(this),
4690
- contextToolbarPlugin(this),
4691
- ...this.contentRules ? [contentRulesPlugin(this.contentRules)] : [],
4692
- ...pluginPm,
4693
- ...options.prosemirrorPlugins ?? []
4694
- ]
5134
+ plugins: initialPlugins
4695
5135
  });
4696
5136
  this.editable = options.editable ?? true;
5137
+ this.disabled = options.disabled ?? false;
4697
5138
  this.pasteAsText = options.pasteAsText ?? false;
4698
5139
  const handleTransaction = this.handleTransaction.bind(this);
4699
5140
  this.view = new EditorView(contentHost, {
4700
5141
  state,
4701
- editable: () => this.editable,
5142
+ editable: () => this.isEditable(),
4702
5143
  attributes: {
4703
5144
  class: "nova-prosemirror",
4704
5145
  role: "textbox",
@@ -4718,11 +5159,16 @@ var Editor = class {
4718
5159
  image: (node, view, getPos) => new ImageView(node, view, getPos, this)
4719
5160
  },
4720
5161
  handleDOMEvents: {
4721
- focus: () => (this.emit("focus"), false),
4722
- blur: () => (this.emit("blur"), false)
5162
+ focus: (_view, event) => (this.emit("focus", { event }), false),
5163
+ blur: (_view, event) => (this.emit("blur", { event }), false)
5164
+ },
5165
+ handleKeyDown: (_view, event) => {
5166
+ this.emit("keydown", { event });
5167
+ return event.defaultPrevented;
4723
5168
  }
4724
5169
  });
4725
5170
  this.root.classList.toggle("nova-readonly", !this.editable);
5171
+ this.applyDisabled();
4726
5172
  registerBuiltins(this);
4727
5173
  registerMenuItems(this);
4728
5174
  if (options.slashCommands !== false) registerSlashCommands(this, options.slashCommands ?? []);
@@ -4747,7 +5193,60 @@ var Editor = class {
4747
5193
  if (!this.statusbar) statusbarHost.remove();
4748
5194
  if (options.onChange) this.on("change", options.onChange);
4749
5195
  this.updatePlaceholder();
4750
- this.ready = resolved.loaders.length ? this.loadLazyPlugins(resolved.loaders) : Promise.resolve();
5196
+ const contentCss = this.applyContentStyles();
5197
+ this.ready = Promise.all([
5198
+ resolved.loaders.length ? this.loadLazyPlugins(resolved.loaders) : void 0,
5199
+ contentCss,
5200
+ // Очистка вставки из Office — отдельный чанк, грузится в фоне (см. paste.ts).
5201
+ loadPasteCleaner(),
5202
+ // Механика таблиц — отдельный чанк (~10 КБ gzip), грузится в фоне (см. tables.ts).
5203
+ this.installTables(tablesAnchor)
5204
+ ]).then(() => {
5205
+ if (!this.destroyed) this.emit("init");
5206
+ });
5207
+ }
5208
+ /**
5209
+ * Подключить механику таблиц (выделение ячеек, ширина колонок, Tab по ячейкам) после её загрузки —
5210
+ * на место перед `anchor`, как если бы плагины были в начальном состоянии.
5211
+ */
5212
+ async installTables(anchor) {
5213
+ const tables = await loadTables();
5214
+ if (!tables || this.destroyed) return;
5215
+ const { state } = this.view;
5216
+ const at = state.plugins.indexOf(anchor);
5217
+ const plugins = [...state.plugins];
5218
+ plugins.splice(at < 0 ? plugins.length : at, 0, ...tables.tablePlugins());
5219
+ reconfigurePlugins(this.view, plugins);
5220
+ this.updateUI();
5221
+ }
5222
+ /** contentStyle сразу, contentCss — по мере загрузки. Каждый редактор — своя область. */
5223
+ applyContentStyles() {
5224
+ const { contentStyle, contentCss } = this.options;
5225
+ const files = contentCss === void 0 ? [] : Array.isArray(contentCss) ? contentCss : [contentCss];
5226
+ if (!contentStyle && !files.length) return void 0;
5227
+ const id = `nova-cs-${++contentScopeId}`;
5228
+ this.root.classList.add(id);
5229
+ const scope = `.nova-editor.${id} .nova-prosemirror`;
5230
+ const sheets = files.map(() => "");
5231
+ let detach = null;
5232
+ const apply = () => {
5233
+ if (this.destroyed) return;
5234
+ detach?.();
5235
+ detach = attachCss(this.root, scopeCss([...sheets, contentStyle ?? ""].join("\n"), scope));
5236
+ };
5237
+ this.cleanups.push(() => detach?.());
5238
+ apply();
5239
+ if (!files.length) return void 0;
5240
+ return Promise.all(
5241
+ files.map(
5242
+ (url, index) => loadCss(url).then(
5243
+ (css) => {
5244
+ sheets[index] = css;
5245
+ },
5246
+ (error) => console.warn(`[nova] contentCss: could not load ${url}`, error)
5247
+ )
5248
+ )
5249
+ ).then(apply);
4751
5250
  }
4752
5251
  // ---------- плагины ----------
4753
5252
  /** Разрешён ли контрол/команда/тег по ограничениям контента (без ограничений — всегда да). */
@@ -4761,11 +5260,12 @@ var Editor = class {
4761
5260
  * Схема с узлами и марками плагинов. Конфликт имён — ошибка конфигурации: сообщаем и работаем
4762
5261
  * на базовой схеме, чтобы редактор всё равно открылся.
4763
5262
  */
4764
- buildSchema(plugins) {
5263
+ buildSchema(plugins, classFilter, htmlRules) {
4765
5264
  const nodes = {};
4766
5265
  const marks = {};
4767
5266
  for (const plugin of plugins) {
4768
- for (const [name, spec] of Object.entries(plugin.nodes ?? {})) {
5267
+ const pluginNodes = typeof plugin.nodes === "function" ? plugin.nodes(this) : plugin.nodes;
5268
+ for (const [name, spec] of Object.entries(pluginNodes ?? {})) {
4769
5269
  if (name in nodes) reportPluginError(`Node "${name}" is defined by several plugins`);
4770
5270
  else nodes[name] = spec;
4771
5271
  }
@@ -4775,10 +5275,10 @@ var Editor = class {
4775
5275
  }
4776
5276
  }
4777
5277
  try {
4778
- return createSchema({ nodes, marks });
5278
+ return createSchema({ nodes, marks }, classFilter, htmlRules, this.direction);
4779
5279
  } catch (error) {
4780
5280
  reportPluginError("Failed to build the document schema from plugins", error);
4781
- return createSchema();
5281
+ return createSchema({}, classFilter, htmlRules, this.direction);
4782
5282
  }
4783
5283
  }
4784
5284
  collectPmPlugins(plugin) {
@@ -4823,8 +5323,7 @@ var Editor = class {
4823
5323
  errors.forEach((message) => reportPluginError(message));
4824
5324
  const extraPm = ordered.flatMap((plugin) => this.collectPmPlugins(plugin));
4825
5325
  if (extraPm.length) {
4826
- const state = this.view.state;
4827
- this.view.updateState(state.reconfigure({ plugins: [...state.plugins, ...extraPm] }));
5326
+ reconfigurePlugins(this.view, [...this.view.state.plugins, ...extraPm]);
4828
5327
  }
4829
5328
  ordered.forEach((plugin) => {
4830
5329
  this.registerCommands(plugin);
@@ -4866,8 +5365,14 @@ var Editor = class {
4866
5365
  this.statusbar?.update(tr.docChanged);
4867
5366
  this.searchBar?.update();
4868
5367
  this.updatePlaceholder();
4869
- if (tr.docChanged) this.emit("change");
4870
- if (tr.selectionSet || tr.docChanged) this.emit("selectionChange");
5368
+ if (tr.docChanged) {
5369
+ this.emit("change", { transaction: tr });
5370
+ const programmatic = tr.getMeta(API_CHANGE_META) || tr.getMeta(REMOTE_CHANGE_META);
5371
+ if (!programmatic && tr.getMeta("addToHistory") !== false) {
5372
+ this.emit("input", { transaction: tr });
5373
+ }
5374
+ }
5375
+ if (tr.selectionSet || tr.docChanged) this.emit("selectionChange", { transaction: tr });
4871
5376
  }
4872
5377
  updatePlaceholder() {
4873
5378
  const doc = this.view.state.doc;
@@ -4887,10 +5392,47 @@ var Editor = class {
4887
5392
  }
4888
5393
  /** Заменить содержимое. По умолчанию попадает в историю undo. */
4889
5394
  setContent(content, { addToHistory = true } = {}) {
4890
- const doc = parseContent(this.schema, content);
5395
+ const detail = { content };
5396
+ this.emit("beforeSetContent", detail);
5397
+ const doc = parseContent(this.schema, detail.content);
4891
5398
  const tr = this.view.state.tr.replaceWith(0, this.view.state.doc.content.size, doc.content);
5399
+ tr.setMeta(API_CHANGE_META, true);
4892
5400
  if (!addToHistory) tr.setMeta("addToHistory", false);
4893
5401
  this.view.dispatch(tr);
5402
+ this.emit("setContent", { content: detail.content });
5403
+ }
5404
+ /**
5405
+ * Вставить HTML в позицию курсора (как insertContent в TinyMCE). HTML разбирается схемой
5406
+ * редактора — как вставка: без скриптов, опасных ссылок и лишних тегов.
5407
+ * Блоки (абзацы, таблицы) встают отдельными блоками. Таблица, вставляемая при курсоре
5408
+ * внутри таблицы, встаёт после неё (а не заменяет её ячейки).
5409
+ */
5410
+ insertContent(html) {
5411
+ if (!this.isEditable()) return false;
5412
+ const template = document.createElement("template");
5413
+ template.innerHTML = html;
5414
+ const container = document.createElement("div");
5415
+ container.append(template.content);
5416
+ const parser = parserFor(this.schema);
5417
+ const hasBlocks = [...container.children].some((el) => INSERT_BLOCK_TAGS.has(el.tagName));
5418
+ const { state } = this.view;
5419
+ const slice = hasBlocks ? new Slice2(parser.parse(container).content, 0, 0) : parser.parseSlice(container);
5420
+ let hasTable = false;
5421
+ slice.content.descendants((node) => {
5422
+ if (node.type.spec.tableRole === "table") hasTable = true;
5423
+ return !hasTable;
5424
+ });
5425
+ const { $from } = state.selection;
5426
+ let tableDepth = 0;
5427
+ for (let depth = 1; depth <= $from.depth; depth++) {
5428
+ if ($from.node(depth).type.spec.tableRole === "table") {
5429
+ tableDepth = depth;
5430
+ break;
5431
+ }
5432
+ }
5433
+ const tr = hasTable && tableDepth ? state.tr.insert($from.after(tableDepth), slice.content) : state.tr.replaceSelection(slice);
5434
+ this.view.dispatch(tr.setMeta(API_CHANGE_META, true).scrollIntoView());
5435
+ return true;
4894
5436
  }
4895
5437
  isEmpty() {
4896
5438
  return this.view.dom.classList.contains("nova-empty");
@@ -4922,6 +5464,13 @@ var Editor = class {
4922
5464
  isActive(command) {
4923
5465
  return isCommandActive(this.view.state, command);
4924
5466
  }
5467
+ /**
5468
+ * Состояние именованной команды для своего тулбара: активна ли (подсветка кнопки) и доступна ли
5469
+ * сейчас. Аналог queryCommandState / queryCommandEnabled.
5470
+ */
5471
+ getCommandState(command) {
5472
+ return { active: this.isActive(command), enabled: this.isEditable() && this.can(command) };
5473
+ }
4925
5474
  focus() {
4926
5475
  if (!this.destroyed) this.view.focus();
4927
5476
  }
@@ -4940,8 +5489,32 @@ var Editor = class {
4940
5489
  closeSearch() {
4941
5490
  this.searchBar.close();
4942
5491
  }
5492
+ /** Можно ли сейчас править текст: не «только чтение» и не отключён. */
4943
5493
  isEditable() {
4944
- return this.editable;
5494
+ return this.editable && !this.disabled;
5495
+ }
5496
+ isDisabled() {
5497
+ return this.disabled;
5498
+ }
5499
+ /** Отключить или включить редактор (как disabled у поля формы). */
5500
+ setDisabled(value) {
5501
+ if (this.disabled === value) return;
5502
+ this.disabled = value;
5503
+ this.view.setProps({});
5504
+ this.applyDisabled();
5505
+ if (value) {
5506
+ this.ui.closePopover();
5507
+ this.view.dom.blur();
5508
+ }
5509
+ this.toolbar?.update();
5510
+ this.emit("editableChange");
5511
+ }
5512
+ applyDisabled() {
5513
+ this.root.classList.toggle("nova-disabled", this.disabled);
5514
+ if (this.disabled) this.root.setAttribute("aria-disabled", "true");
5515
+ else this.root.removeAttribute("aria-disabled");
5516
+ if (this.disabled) this.view.dom.setAttribute("tabindex", "-1");
5517
+ else this.view.dom.removeAttribute("tabindex");
4945
5518
  }
4946
5519
  setEditable(value) {
4947
5520
  if (this.editable === value) return;
@@ -4962,8 +5535,14 @@ var Editor = class {
4962
5535
  off(event, listener) {
4963
5536
  this.listeners.get(event)?.delete(listener);
4964
5537
  }
4965
- emit(event) {
4966
- for (const listener of this.listeners.get(event) ?? []) listener(this);
5538
+ emit(event, ...[detail]) {
5539
+ for (const listener of this.listeners.get(event) ?? []) {
5540
+ try {
5541
+ listener(this, detail);
5542
+ } catch (error) {
5543
+ reportPluginError(`Listener for "${event}" failed`, error);
5544
+ }
5545
+ }
4967
5546
  }
4968
5547
  destroy() {
4969
5548
  if (this.destroyed) return;
@@ -4990,8 +5569,45 @@ var Editor = class {
4990
5569
  function reportPluginError(message, error) {
4991
5570
  console.error(`[nova] ${message}`, ...error === void 0 ? [] : [error]);
4992
5571
  }
5572
+ function attrValid(spec, value) {
5573
+ const validate = spec?.validate;
5574
+ if (!validate) return true;
5575
+ if (typeof validate === "function") {
5576
+ try {
5577
+ validate(value);
5578
+ return true;
5579
+ } catch {
5580
+ return false;
5581
+ }
5582
+ }
5583
+ const type = value === null ? "null" : typeof value;
5584
+ return validate.split("|").includes(type);
5585
+ }
5586
+ function sanitizeAttrs(specs, attrs) {
5587
+ if (!attrs || typeof attrs !== "object" || !specs) return attrs;
5588
+ return Object.fromEntries(
5589
+ Object.entries(attrs).filter(([name, value]) => attrValid(specs[name], value))
5590
+ );
5591
+ }
5592
+ function sanitizeJSON(schema2, json) {
5593
+ const type = schema2.nodes[json.type];
5594
+ const out = { ...json };
5595
+ if (type) out.attrs = sanitizeAttrs(type.spec.attrs, json.attrs);
5596
+ if (Array.isArray(json.marks)) {
5597
+ out.marks = json.marks.map((mark) => {
5598
+ const markType = mark && schema2.marks[mark.type];
5599
+ return markType ? { ...mark, attrs: sanitizeAttrs(markType.spec.attrs, mark.attrs) } : mark;
5600
+ });
5601
+ }
5602
+ if (Array.isArray(json.content)) {
5603
+ out.content = json.content.map(
5604
+ (child) => child && typeof child === "object" ? sanitizeJSON(schema2, child) : child
5605
+ );
5606
+ }
5607
+ return out;
5608
+ }
4993
5609
  function parseContent(schema2, content) {
4994
- if (typeof content !== "string") return PMNode.fromJSON(schema2, content);
5610
+ if (typeof content !== "string") return PMNode.fromJSON(schema2, sanitizeJSON(schema2, content));
4995
5611
  const container = document.createElement("div");
4996
5612
  const template = document.createElement("template");
4997
5613
  template.innerHTML = content;
@@ -5003,10 +5619,7 @@ function createEditor(options) {
5003
5619
  }
5004
5620
 
5005
5621
  export {
5006
- en,
5007
- ru,
5008
- registerLanguage,
5009
- createTranslator,
5622
+ Formatter,
5010
5623
  htmlToPlainText,
5011
5624
  parserFor,
5012
5625
  DEFAULT_MENUS,
@@ -5042,8 +5655,10 @@ export {
5042
5655
  defaultSlashCommands,
5043
5656
  rankSlashCommands,
5044
5657
  countWords,
5658
+ REMOTE_CHANGE_META,
5659
+ API_CHANGE_META,
5045
5660
  Editor,
5046
5661
  parseContent,
5047
5662
  createEditor
5048
5663
  };
5049
- //# sourceMappingURL=chunk-55LD2TT2.js.map
5664
+ //# sourceMappingURL=chunk-DWZLSZDG.js.map