@novaprose/core 0.5.3 → 0.6.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 (47) hide show
  1. package/README.md +51 -17
  2. package/dist/{advlist-FH3K3AAQ.js → advlist-K2U3VPH2.js} +3 -3
  3. package/dist/{autolink-IDJWAL2V.js → autolink-XWDTLY37.js} +2 -2
  4. package/dist/{autoresize-4ZEPQCHP.js → autoresize-UB3GOA6D.js} +2 -2
  5. package/dist/{autosave-DH7SO4UQ.js → autosave-MWNRUNU3.js} +3 -3
  6. package/dist/{charmap-F7EVJ56K.js → charmap-ADLYOIB3.js} +3 -3
  7. package/dist/{chunk-6AL2IS6V.js → chunk-435CRWKA.js} +69 -8
  8. package/dist/chunk-435CRWKA.js.map +1 -0
  9. package/dist/{chunk-55LD2TT2.js → chunk-46RIM5KP.js} +932 -32
  10. package/dist/chunk-46RIM5KP.js.map +1 -0
  11. package/dist/{chunk-YZPJQB3I.js → chunk-7ON7PR5R.js} +106 -25
  12. package/dist/chunk-7ON7PR5R.js.map +1 -0
  13. package/dist/{chunk-6GWG2BLC.js → chunk-HPLT3XRZ.js} +1 -1
  14. package/dist/chunk-HPLT3XRZ.js.map +1 -0
  15. package/dist/{chunk-MOO4PJGI.js → chunk-NPKAIW34.js} +11 -1
  16. package/dist/{chunk-MOO4PJGI.js.map → chunk-NPKAIW34.js.map} +1 -1
  17. package/dist/{directionality-MF5HDXH3.js → directionality-XOHJFSL6.js} +3 -3
  18. package/dist/{emoticons-SONBUCFV.js → emoticons-TP4N4ZGY.js} +3 -3
  19. package/dist/index.cjs +1424 -162
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +248 -11
  22. package/dist/index.d.ts +248 -11
  23. package/dist/index.js +212 -25
  24. package/dist/index.js.map +1 -1
  25. package/dist/{insertdatetime-X2T4ZY6R.js → insertdatetime-T4SEMQWP.js} +3 -3
  26. package/dist/{nonbreaking-PP4KIJSR.js → nonbreaking-HG5HV6AL.js} +3 -3
  27. package/dist/{quickbars-3WKHLKAR.js → quickbars-4NU4SIPL.js} +5 -5
  28. package/dist/{revisionhistory-FYRVDGRA.js → revisionhistory-3YQPLPLM.js} +6 -6
  29. package/dist/{visualblocks-NPTMWFXD.js → visualblocks-RTAYJOGR.js} +3 -3
  30. package/package.json +1 -1
  31. package/src/style.css +106 -0
  32. package/dist/chunk-55LD2TT2.js.map +0 -1
  33. package/dist/chunk-6AL2IS6V.js.map +0 -1
  34. package/dist/chunk-6GWG2BLC.js.map +0 -1
  35. package/dist/chunk-YZPJQB3I.js.map +0 -1
  36. /package/dist/{advlist-FH3K3AAQ.js.map → advlist-K2U3VPH2.js.map} +0 -0
  37. /package/dist/{autolink-IDJWAL2V.js.map → autolink-XWDTLY37.js.map} +0 -0
  38. /package/dist/{autoresize-4ZEPQCHP.js.map → autoresize-UB3GOA6D.js.map} +0 -0
  39. /package/dist/{autosave-DH7SO4UQ.js.map → autosave-MWNRUNU3.js.map} +0 -0
  40. /package/dist/{charmap-F7EVJ56K.js.map → charmap-ADLYOIB3.js.map} +0 -0
  41. /package/dist/{directionality-MF5HDXH3.js.map → directionality-XOHJFSL6.js.map} +0 -0
  42. /package/dist/{emoticons-SONBUCFV.js.map → emoticons-TP4N4ZGY.js.map} +0 -0
  43. /package/dist/{insertdatetime-X2T4ZY6R.js.map → insertdatetime-T4SEMQWP.js.map} +0 -0
  44. /package/dist/{nonbreaking-PP4KIJSR.js.map → nonbreaking-HG5HV6AL.js.map} +0 -0
  45. /package/dist/{quickbars-3WKHLKAR.js.map → quickbars-4NU4SIPL.js.map} +0 -0
  46. /package/dist/{revisionhistory-FYRVDGRA.js.map → revisionhistory-3YQPLPLM.js.map} +0 -0
  47. /package/dist/{visualblocks-NPTMWFXD.js.map → visualblocks-RTAYJOGR.js.map} +0 -0
@@ -25,13 +25,15 @@ import {
25
25
  tablePlugins,
26
26
  tableRect,
27
27
  textField
28
- } from "./chunk-6AL2IS6V.js";
28
+ } from "./chunk-435CRWKA.js";
29
29
  import {
30
+ ALIGNMENTS,
31
+ classAttr,
30
32
  createSchema,
31
33
  cssValue,
32
34
  imageSize,
33
35
  schema
34
- } from "./chunk-YZPJQB3I.js";
36
+ } from "./chunk-7ON7PR5R.js";
35
37
  import {
36
38
  formatShortcut,
37
39
  h,
@@ -40,7 +42,7 @@ import {
40
42
  } from "./chunk-HZRIBOPW.js";
41
43
  import {
42
44
  icons
43
- } from "./chunk-MOO4PJGI.js";
45
+ } from "./chunk-NPKAIW34.js";
44
46
  import {
45
47
  commands,
46
48
  getActiveAlign,
@@ -58,7 +60,408 @@ import {
58
60
  loadPlugin,
59
61
  orderPlugins,
60
62
  resolveEntries
61
- } from "./chunk-6GWG2BLC.js";
63
+ } from "./chunk-HPLT3XRZ.js";
64
+
65
+ // src/formats.ts
66
+ import { NodeSelection } from "prosemirror-state";
67
+ import { lift, wrapIn } from "prosemirror-commands";
68
+ var INLINE_MARKS = {
69
+ strong: "bold",
70
+ b: "bold",
71
+ em: "italic",
72
+ i: "italic",
73
+ u: "underline",
74
+ s: "strike",
75
+ strike: "strike",
76
+ del: "strike",
77
+ code: "code",
78
+ sub: "subscript",
79
+ sup: "superscript"
80
+ };
81
+ var INLINE_STYLES = {
82
+ color: { mark: "color", read: cssValue.color },
83
+ "background-color": { mark: "background", read: cssValue.color },
84
+ "font-family": { mark: "font_family", read: cssValue.fontFamily },
85
+ "font-size": { mark: "font_size", read: cssValue.length }
86
+ };
87
+ var BLOCK_TAGS = {
88
+ p: (n) => n.type.name === "paragraph",
89
+ h1: (n) => n.type.name === "heading" && n.attrs.level === 1,
90
+ h2: (n) => n.type.name === "heading" && n.attrs.level === 2,
91
+ h3: (n) => n.type.name === "heading" && n.attrs.level === 3,
92
+ h4: (n) => n.type.name === "heading" && n.attrs.level === 4,
93
+ h5: (n) => n.type.name === "heading" && n.attrs.level === 5,
94
+ h6: (n) => n.type.name === "heading" && n.attrs.level === 6,
95
+ blockquote: (n) => n.type.name === "blockquote",
96
+ pre: (n) => n.type.name === "code_block",
97
+ img: (n) => n.type.name === "image"
98
+ };
99
+ var warned = /* @__PURE__ */ new Set();
100
+ function warnOnce(message) {
101
+ if (warned.has(message)) return;
102
+ warned.add(message);
103
+ console.warn(`[nova] formats: ${message}`);
104
+ }
105
+ function classList(value) {
106
+ if (Array.isArray(value)) return value.flatMap(classList);
107
+ return typeof value === "string" ? value.split(/\s+/).filter(Boolean) : [];
108
+ }
109
+ function formatClasses(specs) {
110
+ const out = [];
111
+ for (const spec of specs) {
112
+ out.push(...classList(spec.classes));
113
+ if ("items" in spec && spec.items) out.push(...formatClasses(spec.items));
114
+ }
115
+ return out;
116
+ }
117
+ var hasClasses = (value, wanted) => {
118
+ const have = classList(value);
119
+ return wanted.every((c) => have.includes(c));
120
+ };
121
+ var withClasses = (value, add) => {
122
+ const merged = [.../* @__PURE__ */ new Set([...classList(value), ...add])];
123
+ return merged.length ? merged.join(" ") : null;
124
+ };
125
+ var withoutClasses = (value, drop) => {
126
+ const rest = classList(value).filter((c) => !drop.includes(c));
127
+ return rest.length ? rest.join(" ") : null;
128
+ };
129
+ function blockStyles(spec) {
130
+ const out = {};
131
+ for (const [prop, value] of Object.entries(spec.styles ?? {})) {
132
+ if (prop === "text-align" && ALIGNMENTS.includes(value))
133
+ out.align = value;
134
+ else if (prop === "line-height" && cssValue.lineHeight(value))
135
+ out.lineHeight = cssValue.lineHeight(value);
136
+ else warnOnce(`style "${prop}" is not supported on blocks`);
137
+ }
138
+ return out;
139
+ }
140
+ function inlineMarks(state, spec) {
141
+ const marks = marksOf(state);
142
+ const out = [];
143
+ if (spec.inline && spec.inline !== "span") {
144
+ const type = marks[INLINE_MARKS[spec.inline]];
145
+ if (type) out.push(type.create());
146
+ }
147
+ const classes = classList(spec.classes);
148
+ if (classes.length && marks.span_class)
149
+ out.push(marks.span_class.create({ class: classes.join(" ") }));
150
+ for (const [prop, raw] of Object.entries(spec.styles ?? {})) {
151
+ const style = INLINE_STYLES[prop];
152
+ const value = style?.read(raw);
153
+ const type = style ? marks[style.mark] : void 0;
154
+ if (type && value) out.push(type.create({ value }));
155
+ else warnOnce(`style "${prop}: ${raw}" is not supported on text`);
156
+ }
157
+ return out;
158
+ }
159
+ var selectorTags = (spec) => (spec.selector ?? "").split(",").map((s) => s.trim().toLowerCase()).filter((tag) => {
160
+ if (BLOCK_TAGS[tag]) return true;
161
+ warnOnce(`selector "${tag}" is not supported`);
162
+ return false;
163
+ });
164
+ function selectedNodes(state, tags) {
165
+ const out = [];
166
+ const matches = (node) => tags.some((tag) => BLOCK_TAGS[tag](node));
167
+ const { selection } = state;
168
+ if (selection instanceof NodeSelection && matches(selection.node)) {
169
+ return [{ node: selection.node, pos: selection.from }];
170
+ }
171
+ const { $from, from, to } = selection;
172
+ for (let depth = $from.depth; depth > 0; depth--) {
173
+ const node = $from.node(depth);
174
+ if (matches(node)) out.push({ node, pos: $from.before(depth) });
175
+ }
176
+ state.doc.nodesBetween(from, to, (node, pos) => {
177
+ if (matches(node) && !out.some((o) => o.pos === pos)) out.push({ node, pos });
178
+ });
179
+ return out;
180
+ }
181
+ function textBlocks(state) {
182
+ const out = [];
183
+ const { from, to } = state.selection;
184
+ state.doc.nodesBetween(from, to, (node, pos) => {
185
+ if (node.isTextblock) {
186
+ out.push({ node, pos });
187
+ return false;
188
+ }
189
+ return true;
190
+ });
191
+ return out;
192
+ }
193
+ function blockquoteAt(state) {
194
+ const { $from } = state.selection;
195
+ for (let depth = $from.depth; depth > 0; depth--) {
196
+ const node = $from.node(depth);
197
+ if (node.type.name === "blockquote") return { node, pos: $from.before(depth) };
198
+ }
199
+ return null;
200
+ }
201
+ function keepBlockStyle(attrs) {
202
+ return {
203
+ align: attrs.align ?? null,
204
+ lineHeight: attrs.lineHeight ?? null,
205
+ dir: attrs.dir ?? null
206
+ };
207
+ }
208
+ var Formatter = class {
209
+ constructor(editor, allowedClasses) {
210
+ this.editor = editor;
211
+ this.allowedClasses = allowedClasses;
212
+ }
213
+ editor;
214
+ allowedClasses;
215
+ registry = /* @__PURE__ */ new Map();
216
+ /** Зарегистрировать именованный формат (одно описание или несколько вариантов). */
217
+ register(name, spec) {
218
+ const specs = Array.isArray(spec) ? spec : [spec];
219
+ this.registry.set(name, specs);
220
+ formatClasses(specs).forEach((c) => this.allowedClasses.add(c));
221
+ }
222
+ unregister(name) {
223
+ this.registry.delete(name);
224
+ }
225
+ has(name) {
226
+ return this.registry.has(name);
227
+ }
228
+ get(name) {
229
+ return this.registry.get(name);
230
+ }
231
+ resolve(format) {
232
+ if (typeof format !== "string") return [format];
233
+ const specs = this.registry.get(format);
234
+ if (!specs) warnOnce(`unknown format "${format}"`);
235
+ return specs ?? [];
236
+ }
237
+ /** Можно ли применить формат к выделению (для selector — есть ли подходящие элементы). */
238
+ canApply(format) {
239
+ if (!this.editor.isEditable()) return false;
240
+ const state = this.editor.view.state;
241
+ return this.resolve(format).some((spec) => canApply(state, spec));
242
+ }
243
+ /** Подходит ли выделение под формат. */
244
+ match(format) {
245
+ const state = this.editor.view.state;
246
+ return this.resolve(format).some((spec) => matchSpec(state, spec));
247
+ }
248
+ apply(format) {
249
+ if (!this.editor.isEditable()) return false;
250
+ const specs = this.resolve(format);
251
+ if (!specs.length) return false;
252
+ const spec = specs.find((s) => canApply(this.editor.view.state, s)) ?? specs[0];
253
+ return this.run((state, tr) => applySpec(state, tr, spec));
254
+ }
255
+ remove(format) {
256
+ if (!this.editor.isEditable()) return false;
257
+ const specs = this.resolve(format);
258
+ if (!specs.length) return false;
259
+ return this.run((state, tr) => specs.forEach((spec) => removeSpec(state, tr, spec)));
260
+ }
261
+ toggle(format) {
262
+ return this.match(format) ? this.remove(format) : this.apply(format);
263
+ }
264
+ run(fn) {
265
+ const { view } = this.editor;
266
+ const tr = view.state.tr;
267
+ const result = fn(view.state, tr);
268
+ if (result === false) return false;
269
+ if (tr.docChanged || tr.storedMarksSet) view.dispatch(tr.scrollIntoView());
270
+ view.focus();
271
+ return true;
272
+ }
273
+ };
274
+ function canApply(state, spec) {
275
+ if (spec.selector) return selectedNodes(state, selectorTags(spec)).length > 0;
276
+ return true;
277
+ }
278
+ function hasBlockStyles(node, spec) {
279
+ if (node.type.name === "image") return true;
280
+ return Object.entries(blockStyles(spec)).every(([key3, value]) => node.attrs[key3] === value);
281
+ }
282
+ function matchSpec(state, spec) {
283
+ const classes = classList(spec.classes);
284
+ if (spec.block) {
285
+ if (spec.block === "blockquote") {
286
+ const quote = blockquoteAt(state);
287
+ return !!quote && hasClasses(quote.node.attrs.class, classes);
288
+ }
289
+ const node = state.selection.$from.parent;
290
+ return BLOCK_TAGS[spec.block](node) && hasClasses(node.attrs.class, classes) && hasBlockStyles(node, spec);
291
+ }
292
+ if (spec.selector) {
293
+ const nodes = selectedNodes(state, selectorTags(spec));
294
+ return nodes.length > 0 && nodes.some(({ node }) => hasClasses(node.attrs.class, classes) && hasBlockStyles(node, spec));
295
+ }
296
+ if (spec.inline) {
297
+ const wanted = inlineMarks(state, spec);
298
+ if (!wanted.length) return false;
299
+ const { $from, empty, from, to } = state.selection;
300
+ if (empty) {
301
+ const marks = state.storedMarks ?? $from.marks();
302
+ return wanted.every((mark) => marks.some((m) => markCovers(m, mark)));
303
+ }
304
+ let found = false;
305
+ let all = true;
306
+ state.doc.nodesBetween(from, to, (node) => {
307
+ if (!node.isText) return;
308
+ found = true;
309
+ if (!wanted.every((mark) => node.marks.some((m) => markCovers(m, mark)))) all = false;
310
+ });
311
+ return found && all;
312
+ }
313
+ return false;
314
+ }
315
+ function markCovers(m, mark) {
316
+ if (m.type !== mark.type) return false;
317
+ if (mark.type.name === "span_class")
318
+ return hasClasses(m.attrs.class, classList(mark.attrs.class));
319
+ return mark.attrs.value === void 0 || m.attrs.value === mark.attrs.value;
320
+ }
321
+ function applySpec(state, tr, spec) {
322
+ const classes = classList(spec.classes);
323
+ const nodes = nodesOf(state);
324
+ if (spec.block === "blockquote") {
325
+ const quote = blockquoteAt(state);
326
+ if (quote) {
327
+ tr.setNodeMarkup(quote.pos, void 0, {
328
+ ...quote.node.attrs,
329
+ class: withClasses(quote.node.attrs.class, classes)
330
+ });
331
+ return true;
332
+ }
333
+ return wrapIn(nodes.blockquote, { class: withClasses(null, classes) })(
334
+ state,
335
+ (wrapped) => wrapped.steps.forEach((step) => tr.step(step))
336
+ );
337
+ }
338
+ if (spec.block === "pre") {
339
+ for (const { node, pos } of textBlocks(state)) {
340
+ if (node.type !== nodes.code_block)
341
+ tr.setNodeMarkup(pos, nodes.code_block, { language: null });
342
+ }
343
+ return true;
344
+ }
345
+ if (spec.block) {
346
+ const level = spec.block === "p" ? 0 : Number(spec.block.slice(1));
347
+ const type = level ? nodes.heading : nodes.paragraph;
348
+ const styles = blockStyles(spec);
349
+ for (const { node, pos } of textBlocks(state)) {
350
+ if (node.type === nodes.code_block && node.textContent.includes("\n")) continue;
351
+ const sameType = node.type === type && (!level || node.attrs.level === level);
352
+ tr.setNodeMarkup(pos, type, {
353
+ ...keepBlockStyle(node.attrs),
354
+ ...level ? { level } : {},
355
+ ...styles,
356
+ class: withClasses(sameType ? node.attrs.class : null, classes)
357
+ });
358
+ }
359
+ return true;
360
+ }
361
+ if (spec.selector) {
362
+ const styles = blockStyles(spec);
363
+ const targets = selectedNodes(state, selectorTags(spec));
364
+ if (!targets.length) return false;
365
+ for (const { node, pos } of targets) {
366
+ const extra = node.type.name === "image" ? {} : styles;
367
+ tr.setNodeMarkup(pos, void 0, {
368
+ ...node.attrs,
369
+ ...extra,
370
+ class: withClasses(node.attrs.class, classes)
371
+ });
372
+ }
373
+ if (state.selection instanceof NodeSelection)
374
+ tr.setSelection(NodeSelection.create(tr.doc, state.selection.from));
375
+ return true;
376
+ }
377
+ if (spec.inline) {
378
+ const marks = inlineMarks(state, spec);
379
+ if (!marks.length) return false;
380
+ const { empty, ranges } = state.selection;
381
+ if (empty) {
382
+ let stored = state.storedMarks ?? state.selection.$from.marks();
383
+ for (const mark of marks) stored = mark.addToSet(stored);
384
+ tr.setStoredMarks(stored);
385
+ return true;
386
+ }
387
+ for (const { $from, $to } of ranges) {
388
+ for (const mark of marks) tr.addMark($from.pos, $to.pos, mark);
389
+ }
390
+ return true;
391
+ }
392
+ return false;
393
+ }
394
+ function removeSpec(state, tr, spec) {
395
+ const classes = classList(spec.classes);
396
+ const nodes = nodesOf(state);
397
+ if (spec.block === "blockquote") {
398
+ const quote = blockquoteAt(state);
399
+ if (!quote) return;
400
+ const rest = withoutClasses(quote.node.attrs.class, classes);
401
+ if (classes.length && rest !== null) {
402
+ tr.setNodeMarkup(quote.pos, void 0, { ...quote.node.attrs, class: rest });
403
+ return;
404
+ }
405
+ lift(state, (lifted) => lifted.steps.forEach((step) => tr.step(step)));
406
+ return;
407
+ }
408
+ if (spec.block) {
409
+ for (const { node, pos } of textBlocks(state)) {
410
+ if (!BLOCK_TAGS[spec.block](node)) continue;
411
+ tr.setNodeMarkup(pos, nodes.paragraph, {
412
+ ...keepBlockStyle(node.attrs),
413
+ class: spec.block === "p" ? withoutClasses(node.attrs.class, classes) : null
414
+ });
415
+ }
416
+ return;
417
+ }
418
+ if (spec.selector) {
419
+ const styles = blockStyles(spec);
420
+ for (const { node, pos } of selectedNodes(state, selectorTags(spec))) {
421
+ const reset = {};
422
+ if (node.type.name !== "image") {
423
+ if ("align" in styles && node.attrs.align === styles.align) reset.align = null;
424
+ if ("lineHeight" in styles && node.attrs.lineHeight === styles.lineHeight)
425
+ reset.lineHeight = null;
426
+ }
427
+ tr.setNodeMarkup(pos, void 0, {
428
+ ...node.attrs,
429
+ ...reset,
430
+ class: withoutClasses(node.attrs.class, classes)
431
+ });
432
+ }
433
+ if (state.selection instanceof NodeSelection)
434
+ tr.setSelection(NodeSelection.create(tr.doc, state.selection.from));
435
+ return;
436
+ }
437
+ if (spec.inline) {
438
+ const marks = inlineMarks(state, spec);
439
+ const { empty, from, to, $from } = state.selection;
440
+ if (empty) {
441
+ const stored = (state.storedMarks ?? $from.marks()).filter(
442
+ (m) => !marks.some((mark) => markCovers(m, mark))
443
+ );
444
+ tr.setStoredMarks(stored);
445
+ return;
446
+ }
447
+ for (const mark of marks) {
448
+ if (mark.type.name !== "span_class") {
449
+ tr.removeMark(from, to, mark.type);
450
+ continue;
451
+ }
452
+ state.doc.nodesBetween(from, to, (node, pos) => {
453
+ if (!node.isText) return;
454
+ const current = node.marks.find((m) => m.type === mark.type);
455
+ if (!current) return;
456
+ const start = Math.max(pos, from);
457
+ const end = Math.min(pos + node.nodeSize, to);
458
+ tr.removeMark(start, end, mark.type);
459
+ const rest = withoutClasses(current.attrs.class, classList(mark.attrs.class));
460
+ if (rest) tr.addMark(start, end, mark.type.create({ class: rest }));
461
+ });
462
+ }
463
+ }
464
+ }
62
465
 
63
466
  // src/i18n/en.ts
64
467
  var en = {
@@ -94,6 +497,11 @@ var en = {
94
497
  more: "More",
95
498
  moreFormats: "More formatting",
96
499
  blocks: "Text style",
500
+ styles: "Formats",
501
+ "styles.headings": "Headings",
502
+ "styles.inline": "Inline",
503
+ "styles.blocks": "Blocks",
504
+ "styles.align": "Align",
97
505
  paragraph: "Paragraph",
98
506
  h1: "Heading 1",
99
507
  h2: "Heading 2",
@@ -147,6 +555,8 @@ var en = {
147
555
  "image.sizeOriginal": "Original size",
148
556
  "image.delete": "Remove image",
149
557
  "status.words": "{count} words",
558
+ "status.resize": "Resize editor",
559
+ "dialog.browse": "Browse",
150
560
  pasteAsText: "Paste as text",
151
561
  "menu.label": "Menu",
152
562
  "menu.file": "File",
@@ -208,6 +618,8 @@ var en = {
208
618
  "table.sortAsc": "Sort A \u2192 Z, 1 \u2192 9",
209
619
  "table.sortDesc": "Sort Z \u2192 A, 9 \u2192 1",
210
620
  "table.props": "Table properties",
621
+ "table.style": "Style",
622
+ "table.styleDefault": "Default",
211
623
  "table.width": "Width",
212
624
  "table.widthHint": "For example 100% or 600px. Leave empty to fit the content.",
213
625
  "table.invalidWidth": "Enter a width such as 100% or 600px",
@@ -264,6 +676,11 @@ var ru = {
264
676
  more: "\u0415\u0449\u0451",
265
677
  moreFormats: "\u0415\u0449\u0451 \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",
266
678
  blocks: "\u0421\u0442\u0438\u043B\u044C \u0442\u0435\u043A\u0441\u0442\u0430",
679
+ styles: "\u0424\u043E\u0440\u043C\u0430\u0442\u044B",
680
+ "styles.headings": "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0438",
681
+ "styles.inline": "\u0422\u0435\u043A\u0441\u0442",
682
+ "styles.blocks": "\u0411\u043B\u043E\u043A\u0438",
683
+ "styles.align": "\u0412\u044B\u0440\u0430\u0432\u043D\u0438\u0432\u0430\u043D\u0438\u0435",
267
684
  paragraph: "\u041E\u0431\u044B\u0447\u043D\u044B\u0439 \u0442\u0435\u043A\u0441\u0442",
268
685
  h1: "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A 1",
269
686
  h2: "\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A 2",
@@ -317,6 +734,8 @@ var ru = {
317
734
  "image.sizeOriginal": "\u0418\u0441\u0445\u043E\u0434\u043D\u044B\u0439 \u0440\u0430\u0437\u043C\u0435\u0440",
318
735
  "image.delete": "\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435",
319
736
  "status.words": "\u0421\u043B\u043E\u0432: {count}",
737
+ "status.resize": "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u0440\u0430\u0437\u043C\u0435\u0440 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0430",
738
+ "dialog.browse": "\u041E\u0431\u0437\u043E\u0440",
320
739
  pasteAsText: "\u0412\u0441\u0442\u0430\u0432\u043B\u044F\u0442\u044C \u043A\u0430\u043A \u0442\u0435\u043A\u0441\u0442",
321
740
  "menu.label": "\u041C\u0435\u043D\u044E",
322
741
  "menu.file": "\u0424\u0430\u0439\u043B",
@@ -378,6 +797,8 @@ var ru = {
378
797
  "table.sortAsc": "\u0421\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0410 \u2192 \u042F, 1 \u2192 9",
379
798
  "table.sortDesc": "\u0421\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u042F \u2192 \u0410, 9 \u2192 1",
380
799
  "table.props": "\u0421\u0432\u043E\u0439\u0441\u0442\u0432\u0430 \u0442\u0430\u0431\u043B\u0438\u0446\u044B",
800
+ "table.style": "\u0421\u0442\u0438\u043B\u044C",
801
+ "table.styleDefault": "\u041E\u0431\u044B\u0447\u043D\u044B\u0439",
381
802
  "table.width": "\u0428\u0438\u0440\u0438\u043D\u0430",
382
803
  "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
804
  "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",
@@ -455,6 +876,8 @@ function cleanPastedHTML(html, styles = "clean") {
455
876
  removeBreaksBetweenBlocks(root);
456
877
  normalizeEmptyParagraphs(root);
457
878
  wrapCellContent(root);
879
+ if (source !== "web")
880
+ root.querySelectorAll("[class]").forEach((el) => el.removeAttribute("class"));
458
881
  return root.innerHTML;
459
882
  }
460
883
  function parseDeclarations(css) {
@@ -1040,12 +1463,21 @@ function preprocessDOM(root) {
1040
1463
  });
1041
1464
  }
1042
1465
  var NovaDOMParser = class extends DOMParser {
1043
- parse(dom, options) {
1466
+ atomSelector;
1467
+ prepare(dom) {
1044
1468
  preprocessDOM(dom);
1469
+ 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(", ");
1470
+ if (!this.atomSelector || !("querySelectorAll" in dom)) return;
1471
+ dom.querySelectorAll(this.atomSelector).forEach((el) => {
1472
+ el.removeAttribute("style");
1473
+ });
1474
+ }
1475
+ parse(dom, options) {
1476
+ this.prepare(dom);
1045
1477
  return super.parse(dom, options);
1046
1478
  }
1047
1479
  parseSlice(dom, options) {
1048
- preprocessDOM(dom);
1480
+ this.prepare(dom);
1049
1481
  return super.parseSlice(dom, options);
1050
1482
  }
1051
1483
  };
@@ -1064,12 +1496,18 @@ var novaParser = parserFor(schema);
1064
1496
  function createMenu(entries, onDone, label) {
1065
1497
  const items = [];
1066
1498
  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);
1499
+ const hasChecks = entries.some(
1500
+ (e) => (e.type === void 0 || e.type === "item") && e.active !== void 0
1501
+ );
1068
1502
  for (const entry of entries) {
1069
1503
  if (entry.type === "separator") {
1070
1504
  menu.append(h("div", { className: "nova-menu-sep", role: "separator" }));
1071
1505
  continue;
1072
1506
  }
1507
+ if (entry.type === "heading") {
1508
+ menu.append(h("div", { className: "nova-menu-heading", role: "presentation" }, entry.label));
1509
+ continue;
1510
+ }
1073
1511
  const labelEl = h("span", { className: "nova-menu-label" }, entry.label);
1074
1512
  if (entry.labelStyle) labelEl.setAttribute("style", entry.labelStyle);
1075
1513
  const button = h(
@@ -2442,6 +2880,15 @@ function registerTableUi(editor) {
2442
2880
  items: "tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol | tablemergecells tablesplitcells | tablerowheader tablecolheader tablecellbackground | advtablesort tablecellprops tableprops | tabledelete"
2443
2881
  });
2444
2882
  }
2883
+ function classSelect(editor, list, current) {
2884
+ if (!list?.length) return null;
2885
+ const { t } = editor.ui;
2886
+ const options = [{ value: "", label: t("table.styleDefault") }];
2887
+ for (const o of list) if (o.value) options.push({ value: o.value, label: o.title });
2888
+ if (current && !options.some((o) => o.value === current))
2889
+ options.push({ value: current, label: current });
2890
+ return selectField({ label: t("table.style"), value: current ?? "", options });
2891
+ }
2445
2892
  function openTableProps(editor) {
2446
2893
  const { t } = editor.ui;
2447
2894
  const current = getTableProps(editor.view.state);
@@ -2460,15 +2907,17 @@ function openTableProps(editor) {
2460
2907
  { value: "right", label: t("table.alignRight") }
2461
2908
  ]
2462
2909
  });
2910
+ const styles = classSelect(editor, editor.options.tableClassList, current.class ?? null);
2463
2911
  editor.ui.openDialog({
2464
2912
  title: t("table.props"),
2465
- body: h("div", { className: "nova-form" }, width.el, align.el),
2913
+ body: h("div", { className: "nova-form" }, styles?.el ?? null, width.el, align.el),
2466
2914
  submitLabel: t("dialog.save"),
2467
2915
  onSubmit: () => {
2468
2916
  const raw = width.input.value.trim().replace(/^(\d+(\.\d+)?)$/, "$1px");
2469
2917
  const props = {
2470
2918
  width: raw || null,
2471
- align: align.select.value || null
2919
+ align: align.select.value || null,
2920
+ ...styles ? { class: styles.select.value || null } : {}
2472
2921
  };
2473
2922
  return editor.exec(setTableProps(props)) || t("table.invalidWidth");
2474
2923
  }
@@ -2501,9 +2950,10 @@ function openCellProps(editor) {
2501
2950
  hint: t("table.colWidthHint"),
2502
2951
  value: current.width ? String(current.width) : ""
2503
2952
  });
2953
+ const styles = classSelect(editor, editor.options.tableCellClassList, current.class ?? null);
2504
2954
  editor.ui.openDialog({
2505
2955
  title: t("table.cellProps"),
2506
- body: h("div", { className: "nova-form" }, valign.el, type.el, width.el),
2956
+ body: h("div", { className: "nova-form" }, styles?.el ?? null, valign.el, type.el, width.el),
2507
2957
  submitLabel: t("dialog.save"),
2508
2958
  onSubmit: () => {
2509
2959
  const rawWidth = width.input.value.trim();
@@ -2514,7 +2964,8 @@ function openCellProps(editor) {
2514
2964
  setCellProps({
2515
2965
  valign: valign.select.value || null,
2516
2966
  header: type.select.value === "th",
2517
- width: px
2967
+ width: px,
2968
+ ...styles ? { class: styles.select.value || null } : {}
2518
2969
  })
2519
2970
  );
2520
2971
  return true;
@@ -2695,20 +3146,133 @@ function registerBuiltins(editor) {
2695
3146
  onAction: (e) => e.exec(currentBlock() === command ? "paragraph" : command)
2696
3147
  });
2697
3148
  }
3149
+ const BLOCK_COMMANDS = {
3150
+ p: "paragraph",
3151
+ h1: "h1",
3152
+ h2: "h2",
3153
+ h3: "h3",
3154
+ h4: "h4",
3155
+ h5: "h5",
3156
+ h6: "h6",
3157
+ pre: "codeBlock"
3158
+ };
3159
+ const blockList = () => {
3160
+ const custom = editor.options.blockFormats;
3161
+ if (!custom?.length) return blockItems;
3162
+ return custom.flatMap(({ label, block }) => {
3163
+ const command = BLOCK_COMMANDS[block];
3164
+ const item = blockItems.find((i) => i.command === command);
3165
+ return item ? [{ ...item, label }] : [];
3166
+ });
3167
+ };
2698
3168
  registry.addMenuButton("blocks", {
2699
3169
  tooltip: t("blocks"),
2700
- label: () => t(currentBlock()),
3170
+ label: () => blockList().find((i) => i.command === currentBlock())?.label ?? t(currentBlock()),
2701
3171
  minChars: 11,
2702
- isEnabled: (e) => blockItems.some(({ command }) => e.can(command)),
2703
- items: (e) => blockItems.filter(({ command }) => e.isAllowed(command)).map(({ command, style }) => ({
3172
+ isEnabled: (e) => blockList().some(({ command }) => e.can(command)),
3173
+ items: (e) => blockList().filter(({ command }) => e.isAllowed(command)).map(({ command, style, label }) => ({
2704
3174
  id: command,
2705
- label: t(command),
3175
+ label: label ?? t(command),
2706
3176
  labelStyle: style,
2707
3177
  ...SHORTCUTS2[command] ? { shortcut: SHORTCUTS2[command] } : {},
2708
3178
  active: currentBlock() === command,
2709
3179
  onSelect: () => e.exec(command)
2710
3180
  }))
2711
3181
  });
3182
+ const ALIGN_SELECTOR = "p,h1,h2,h3,h4,h5,h6";
3183
+ const defaultStyleFormats = () => [
3184
+ {
3185
+ title: t("styles.headings"),
3186
+ items: [1, 2, 3, 4, 5, 6].map((level) => ({
3187
+ title: t(`h${level}`),
3188
+ block: `h${level}`
3189
+ }))
3190
+ },
3191
+ {
3192
+ title: t("styles.inline"),
3193
+ items: [
3194
+ { title: t("bold"), inline: "strong" },
3195
+ { title: t("italic"), inline: "em" },
3196
+ { title: t("underline"), inline: "u" },
3197
+ { title: t("strike"), inline: "s" },
3198
+ { title: t("superscript"), inline: "sup" },
3199
+ { title: t("subscript"), inline: "sub" },
3200
+ { title: t("code"), inline: "code" }
3201
+ ]
3202
+ },
3203
+ {
3204
+ title: t("styles.blocks"),
3205
+ items: [
3206
+ { title: t("paragraph"), block: "p" },
3207
+ { title: t("blockquote"), block: "blockquote" },
3208
+ { title: t("codeBlock"), block: "pre" }
3209
+ ]
3210
+ },
3211
+ {
3212
+ title: t("styles.align"),
3213
+ items: ["left", "center", "right", "justify"].map((align) => ({
3214
+ title: t(
3215
+ `align${align === "justify" ? "Justify" : align[0].toUpperCase() + align.slice(1)}`
3216
+ ),
3217
+ selector: ALIGN_SELECTOR,
3218
+ styles: { "text-align": align }
3219
+ }))
3220
+ }
3221
+ ];
3222
+ const formatOf = (item) => item.format ?? item;
3223
+ const previewStyle = (item) => {
3224
+ const spec = item.format ? editor.formatter.get(item.format)?.[0] : item;
3225
+ const parts = [];
3226
+ const block = spec?.block;
3227
+ if (block && /^h[1-6]$/.test(block)) parts.push("font-weight: 700");
3228
+ if (spec?.inline === "strong" || spec?.inline === "b") parts.push("font-weight: 700");
3229
+ if (spec?.inline === "em" || spec?.inline === "i") parts.push("font-style: italic");
3230
+ if (spec?.inline === "u") parts.push("text-decoration: underline");
3231
+ if (spec?.inline === "s" || spec?.inline === "strike" || spec?.inline === "del")
3232
+ parts.push("text-decoration: line-through");
3233
+ if (spec?.inline === "code" || block === "pre")
3234
+ parts.push("font-family: ui-monospace, monospace");
3235
+ for (const prop of ["color", "background-color", "font-family"]) {
3236
+ const value = spec?.styles?.[prop];
3237
+ if (value && /^[#\w\s,'"().%-]+$/.test(value)) parts.push(`${prop}: ${value}`);
3238
+ }
3239
+ return parts.join("; ");
3240
+ };
3241
+ const flatStyles = (items) => items.flatMap((item) => item.items ? flatStyles(item.items) : [item]);
3242
+ const styleFormats = () => {
3243
+ const custom = editor.options.styleFormats;
3244
+ if (!custom) return defaultStyleFormats();
3245
+ return editor.options.styleFormatsMerge ? [...defaultStyleFormats(), ...custom] : custom;
3246
+ };
3247
+ registry.addMenuButton("styles", {
3248
+ tooltip: t("styles"),
3249
+ minChars: 10,
3250
+ label: (e) => flatStyles(styleFormats()).find((item) => e.formatter.match(formatOf(item)))?.title ?? t("styles"),
3251
+ items: (e) => {
3252
+ const entries = [];
3253
+ const add = (items, prefix) => {
3254
+ items.forEach((item, index) => {
3255
+ if (item.items) {
3256
+ if (entries.length) entries.push({ type: "separator" });
3257
+ entries.push({ type: "heading", label: item.title });
3258
+ add(item.items, `${prefix}${index}-`);
3259
+ return;
3260
+ }
3261
+ entries.push({
3262
+ id: `style-${prefix}${index}`,
3263
+ label: item.title,
3264
+ labelStyle: previewStyle(item),
3265
+ active: e.formatter.match(formatOf(item)),
3266
+ // Формат по селектору без подходящих элементов (картинка не выделена) — неактивен.
3267
+ disabled: !e.formatter.canApply(formatOf(item)),
3268
+ onSelect: () => e.formatter.toggle(formatOf(item))
3269
+ });
3270
+ });
3271
+ };
3272
+ add(styleFormats(), "");
3273
+ return entries;
3274
+ }
3275
+ });
2712
3276
  const families = editor.options.fontFamilies ?? defaultFontFamilies;
2713
3277
  registry.addMenuButton("fontfamily", {
2714
3278
  tooltip: t("fontFamily"),
@@ -3495,6 +4059,8 @@ function createStatusbar(editor, host) {
3495
4059
  const path = h("div", { className: "nova-path", "aria-hidden": "true" });
3496
4060
  const words = h("div", { className: "nova-wordcount", "aria-live": "off" });
3497
4061
  host.append(path, words);
4062
+ const resize = editor.options.resize;
4063
+ const removeHandle = resize ? createResizeHandle(editor, host, resize === "both") : null;
3498
4064
  let timer = null;
3499
4065
  const updateWords = () => {
3500
4066
  const doc = editor.view.state.doc;
@@ -3528,17 +4094,235 @@ function createStatusbar(editor, host) {
3528
4094
  update,
3529
4095
  destroy: () => {
3530
4096
  if (timer) clearTimeout(timer);
4097
+ removeHandle?.();
3531
4098
  host.replaceChildren();
3532
4099
  }
3533
4100
  };
3534
4101
  }
4102
+ var MIN_HEIGHT = 100;
4103
+ var MIN_WIDTH = 200;
4104
+ var KEY_STEP = 20;
4105
+ function createResizeHandle(editor, host, both) {
4106
+ const root = editor.root;
4107
+ const handle = h("div", {
4108
+ className: "nova-resize-handle",
4109
+ role: "separator",
4110
+ tabIndex: 0,
4111
+ "aria-orientation": "horizontal",
4112
+ "aria-label": editor.ui.t("status.resize")
4113
+ });
4114
+ handle.append(icon(both ? icons.resizeHandleBoth : icons.resizeHandle));
4115
+ root.dataset.resize = both ? "both" : "vertical";
4116
+ host.append(handle);
4117
+ const setSize = (height, width) => {
4118
+ root.style.boxSizing = "border-box";
4119
+ root.style.height = `${Math.max(MIN_HEIGHT, Math.round(height))}px`;
4120
+ if (both && width !== void 0) {
4121
+ const max = root.parentElement?.clientWidth || Infinity;
4122
+ root.style.width = `${Math.min(max, Math.max(MIN_WIDTH, Math.round(width)))}px`;
4123
+ }
4124
+ handle.setAttribute("aria-valuenow", String(root.offsetHeight));
4125
+ };
4126
+ let start = null;
4127
+ const onDown = (event) => {
4128
+ if (editor.isDisabled()) return;
4129
+ event.preventDefault();
4130
+ handle.setPointerCapture(event.pointerId);
4131
+ start = {
4132
+ x: event.clientX,
4133
+ y: event.clientY,
4134
+ height: root.offsetHeight,
4135
+ width: root.offsetWidth
4136
+ };
4137
+ };
4138
+ const onMove = (event) => {
4139
+ if (!start) return;
4140
+ setSize(start.height + event.clientY - start.y, start.width + event.clientX - start.x);
4141
+ };
4142
+ const onUp = (event) => {
4143
+ if (!start) return;
4144
+ start = null;
4145
+ if (handle.hasPointerCapture(event.pointerId)) handle.releasePointerCapture(event.pointerId);
4146
+ };
4147
+ const onKey = (event) => {
4148
+ const dy = event.key === "ArrowDown" ? KEY_STEP : event.key === "ArrowUp" ? -KEY_STEP : 0;
4149
+ const dx = both ? event.key === "ArrowRight" ? KEY_STEP : event.key === "ArrowLeft" ? -KEY_STEP : 0 : 0;
4150
+ if (!dx && !dy) return;
4151
+ event.preventDefault();
4152
+ setSize(root.offsetHeight + dy, root.offsetWidth + dx);
4153
+ };
4154
+ handle.addEventListener("pointerdown", onDown);
4155
+ handle.addEventListener("pointermove", onMove);
4156
+ handle.addEventListener("pointerup", onUp);
4157
+ handle.addEventListener("pointercancel", onUp);
4158
+ handle.addEventListener("keydown", onKey);
4159
+ return () => {
4160
+ handle.remove();
4161
+ delete root.dataset.resize;
4162
+ };
4163
+ }
4164
+
4165
+ // src/content-css.ts
4166
+ var GLOBAL_AT_RULES = /^@(font-face|(-webkit-)?keyframes|property|counter-style|page|font-feature-values|font-palette-values)\b/i;
4167
+ var GROUP_AT_RULES = /^@(media|supports|container|layer|document|scope)\b/i;
4168
+ function splitTopLevel(css) {
4169
+ const items = [];
4170
+ let i = 0;
4171
+ let start = 0;
4172
+ let depth = 0;
4173
+ let prelude = "";
4174
+ while (i < css.length) {
4175
+ const ch = css[i];
4176
+ if (ch === "/" && css[i + 1] === "*") {
4177
+ const end = css.indexOf("*/", i + 2);
4178
+ const cut = end === -1 ? css.length : end + 2;
4179
+ if (depth === 0) {
4180
+ css = css.slice(0, i) + css.slice(cut);
4181
+ continue;
4182
+ }
4183
+ i = cut;
4184
+ continue;
4185
+ }
4186
+ if (ch === '"' || ch === "'") {
4187
+ i++;
4188
+ while (i < css.length && css[i] !== ch) i += css[i] === "\\" ? 2 : 1;
4189
+ i++;
4190
+ continue;
4191
+ }
4192
+ if (ch === "{") {
4193
+ if (depth === 0) {
4194
+ prelude = css.slice(start, i).trim();
4195
+ start = i + 1;
4196
+ }
4197
+ depth++;
4198
+ } else if (ch === "}") {
4199
+ depth--;
4200
+ if (depth === 0) {
4201
+ items.push({ prelude, body: css.slice(start, i) });
4202
+ start = i + 1;
4203
+ }
4204
+ if (depth < 0) depth = 0;
4205
+ } else if (ch === ";" && depth === 0) {
4206
+ const statement = css.slice(start, i).trim();
4207
+ if (statement) items.push({ prelude: statement, body: null });
4208
+ start = i + 1;
4209
+ }
4210
+ i++;
4211
+ }
4212
+ return items;
4213
+ }
4214
+ function splitSelectors(list) {
4215
+ const parts = [];
4216
+ let depth = 0;
4217
+ let quote = "";
4218
+ let start = 0;
4219
+ for (let i = 0; i < list.length; i++) {
4220
+ const ch = list[i];
4221
+ if (quote) {
4222
+ if (ch === "\\") i++;
4223
+ else if (ch === quote) quote = "";
4224
+ } else if (ch === '"' || ch === "'") quote = ch;
4225
+ else if (ch === "(" || ch === "[") depth++;
4226
+ else if (ch === ")" || ch === "]") depth--;
4227
+ else if (ch === "," && depth === 0) {
4228
+ parts.push(list.slice(start, i));
4229
+ start = i + 1;
4230
+ }
4231
+ }
4232
+ parts.push(list.slice(start));
4233
+ return parts.map((s) => s.trim()).filter(Boolean);
4234
+ }
4235
+ function scopeSelector(selector, scope) {
4236
+ let rest = selector;
4237
+ let root = false;
4238
+ for (; ; ) {
4239
+ const m = rest.match(/^(html|body|:root)(?![\w-])\s*/i);
4240
+ if (!m) break;
4241
+ root = true;
4242
+ rest = rest.slice(m[0].length);
4243
+ }
4244
+ if (!root) return `${scope} ${selector}`;
4245
+ if (/^[.#[:]/.test(rest)) {
4246
+ const end = rest.search(/[\s>+~]/);
4247
+ return end === -1 ? `${scope}${rest}` : `${scope}${rest.slice(0, end)} ${rest.slice(end).trim()}`;
4248
+ }
4249
+ return rest ? `${scope} ${rest}` : scope;
4250
+ }
4251
+ function scopeCss(css, scope) {
4252
+ const out = [];
4253
+ for (const { prelude, body } of splitTopLevel(css)) {
4254
+ if (body === null) {
4255
+ if (/^@layer\b/i.test(prelude)) out.push(`${prelude};`);
4256
+ continue;
4257
+ }
4258
+ if (GLOBAL_AT_RULES.test(prelude)) out.push(`${prelude}{${body}}`);
4259
+ else if (GROUP_AT_RULES.test(prelude)) out.push(`${prelude}{${scopeCss(body, scope)}}`);
4260
+ else if (prelude.startsWith("@"))
4261
+ continue;
4262
+ else {
4263
+ const selectors = splitSelectors(prelude).map((s) => scopeSelector(s, scope));
4264
+ if (selectors.length) out.push(`${selectors.join(", ")}{${body}}`);
4265
+ }
4266
+ }
4267
+ return out.join("\n");
4268
+ }
4269
+ function absolutizeUrls(css, base) {
4270
+ return css.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi, (match, quote, url) => {
4271
+ if (/^(data:|https?:|\/\/|#)/i.test(url)) return match;
4272
+ try {
4273
+ return `url(${quote}${new URL(url, base).href}${quote})`;
4274
+ } catch {
4275
+ return match;
4276
+ }
4277
+ });
4278
+ }
4279
+ var IMPORT = /@import\s+(?:url\(\s*)?(['"]?)([^'")\s;]+)\1\s*\)?([^;]*);/gi;
4280
+ async function loadCss(url, depth = 0) {
4281
+ const base = new URL(url, document.baseURI).href;
4282
+ const response = await fetch(base);
4283
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
4284
+ let css = absolutizeUrls(await response.text(), base);
4285
+ if (depth >= 3) return css.replace(IMPORT, "");
4286
+ const imports = [...css.matchAll(IMPORT)];
4287
+ for (const m of imports) {
4288
+ const media = m[3].trim();
4289
+ let inner = "";
4290
+ try {
4291
+ inner = await loadCss(new URL(m[2], base).href, depth + 1);
4292
+ } catch (error) {
4293
+ console.warn(`[nova] contentCss: could not load ${m[2]}`, error);
4294
+ }
4295
+ css = css.replace(m[0], media ? `@media ${media}{${inner}}` : inner);
4296
+ }
4297
+ return css;
4298
+ }
4299
+ function attachCss(host, css) {
4300
+ const root = host.getRootNode();
4301
+ const canAdopt = "adoptedStyleSheets" in root && typeof CSSStyleSheet !== "undefined" && "replaceSync" in CSSStyleSheet.prototype;
4302
+ if (canAdopt) {
4303
+ try {
4304
+ const sheet = new CSSStyleSheet();
4305
+ sheet.replaceSync(css);
4306
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
4307
+ return () => {
4308
+ root.adoptedStyleSheets = root.adoptedStyleSheets.filter((s) => s !== sheet);
4309
+ };
4310
+ } catch {
4311
+ }
4312
+ }
4313
+ const style = document.createElement("style");
4314
+ style.setAttribute("data-nova-content-css", "");
4315
+ style.textContent = css;
4316
+ host.prepend(style);
4317
+ return () => style.remove();
4318
+ }
3535
4319
 
3536
4320
  // src/editor.ts
3537
4321
  import { dropCursor } from "prosemirror-dropcursor";
3538
4322
  import { gapCursor } from "prosemirror-gapcursor";
3539
4323
  import { history } from "prosemirror-history";
3540
4324
  import { keymap as keymap2 } from "prosemirror-keymap";
3541
- import { Node as PMNode } from "prosemirror-model";
4325
+ import { Node as PMNode, Slice as Slice2 } from "prosemirror-model";
3542
4326
  import { EditorState } from "prosemirror-state";
3543
4327
  import { EditorView } from "prosemirror-view";
3544
4328
 
@@ -3895,7 +4679,7 @@ function linkBubblePlugin(editor) {
3895
4679
  }
3896
4680
 
3897
4681
  // src/ui/context-toolbar.ts
3898
- import { NodeSelection, Plugin as Plugin5, PluginKey as PluginKey5 } from "prosemirror-state";
4682
+ import { NodeSelection as NodeSelection2, Plugin as Plugin5, PluginKey as PluginKey5 } from "prosemirror-state";
3899
4683
  function contextToolbarPlugin(editor) {
3900
4684
  return new Plugin5({
3901
4685
  key: new PluginKey5("nova-context-toolbar"),
@@ -3934,7 +4718,7 @@ function contextToolbarPlugin(editor) {
3934
4718
  };
3935
4719
  const anchorRect = (spec) => {
3936
4720
  const { selection } = view.state;
3937
- if ((spec.position ?? "node") === "node" && selection instanceof NodeSelection) {
4721
+ if ((spec.position ?? "node") === "node" && selection instanceof NodeSelection2) {
3938
4722
  const dom = view.nodeDOM(selection.from);
3939
4723
  return dom?.getBoundingClientRect() ?? null;
3940
4724
  }
@@ -4032,8 +4816,8 @@ function focusContextToolbar(editor) {
4032
4816
  }
4033
4817
 
4034
4818
  // src/ui/image-view.ts
4035
- import { NodeSelection as NodeSelection2 } from "prosemirror-state";
4036
- var MIN_WIDTH = 24;
4819
+ import { NodeSelection as NodeSelection3 } from "prosemirror-state";
4820
+ var MIN_WIDTH2 = 24;
4037
4821
  var ImageView = class {
4038
4822
  constructor(node, view, getPos, editor) {
4039
4823
  this.view = view;
@@ -4067,6 +4851,7 @@ var ImageView = class {
4067
4851
  if (this.img.getAttribute("src") !== safeSrc) this.img.setAttribute("src", safeSrc);
4068
4852
  this.setAttr("alt", alt);
4069
4853
  this.setAttr("title", title);
4854
+ this.setAttr("class", classAttr(this.node.attrs.class).class ?? null);
4070
4855
  const w = imageSize(width);
4071
4856
  const h2 = imageSize(height);
4072
4857
  this.img.style.width = w ? `${w}px` : "";
@@ -4106,14 +4891,14 @@ var ImageView = class {
4106
4891
  const startX = event.clientX;
4107
4892
  const startWidth = rect.width;
4108
4893
  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);
4894
+ const maxWidth = Math.max(MIN_WIDTH2, this.view.dom.clientWidth - 40);
4110
4895
  const direction = corner === "ne" || corner === "se" ? 1 : -1;
4111
4896
  let width = startWidth;
4112
4897
  this.resizing = true;
4113
4898
  this.dom.classList.add("is-resizing");
4114
4899
  const onMove = (e) => {
4115
4900
  width = Math.round(
4116
- Math.min(maxWidth, Math.max(MIN_WIDTH, startWidth + direction * (e.clientX - startX)))
4901
+ Math.min(maxWidth, Math.max(MIN_WIDTH2, startWidth + direction * (e.clientX - startX)))
4117
4902
  );
4118
4903
  this.img.style.width = `${width}px`;
4119
4904
  this.dom.dataset.size = `${width} \xD7 ${Math.round(width * ratio)}`;
@@ -4132,7 +4917,7 @@ var ImageView = class {
4132
4917
  width,
4133
4918
  height: Math.round(width * ratio)
4134
4919
  });
4135
- tr.setSelection(NodeSelection2.create(tr.doc, pos));
4920
+ tr.setSelection(NodeSelection3.create(tr.doc, pos));
4136
4921
  this.view.dispatch(tr);
4137
4922
  };
4138
4923
  handle.addEventListener("pointermove", onMove);
@@ -4576,6 +5361,10 @@ var UiManager = class {
4576
5361
 
4577
5362
  // src/editor.ts
4578
5363
  var htmlSerializer = new HTMLSerializer();
5364
+ var INSERT_BLOCK_TAGS = new Set(
5365
+ "P H1 H2 H3 H4 H5 H6 UL OL TABLE BLOCKQUOTE PRE HR DIV FIGURE".split(" ")
5366
+ );
5367
+ var contentScopeId = 0;
4579
5368
  var Editor = class {
4580
5369
  view;
4581
5370
  root;
@@ -4596,10 +5385,13 @@ var Editor = class {
4596
5385
  contentRules;
4597
5386
  /** Схема документа этого редактора: базовая + узлы и марки синхронных плагинов. */
4598
5387
  schema;
5388
+ /** Форматы: register / apply / remove / toggle / match. */
5389
+ formatter;
4599
5390
  statusbar;
4600
5391
  searchBar;
4601
5392
  destroyed = false;
4602
5393
  editable;
5394
+ disabled;
4603
5395
  pasteAsText;
4604
5396
  constructor(options) {
4605
5397
  this.options = options;
@@ -4666,7 +5458,21 @@ var Editor = class {
4666
5458
  const pluginPm = syncPlugins.flatMap((plugin) => this.collectPmPlugins(plugin));
4667
5459
  const hasRules = options.validElements !== void 0 || options.invalidElements !== void 0 || options.validStyles !== void 0;
4668
5460
  this.contentRules = hasRules ? new ContentRules(options) : null;
4669
- this.schema = this.buildSchema(syncPlugins);
5461
+ const allowedClasses = /* @__PURE__ */ new Set([
5462
+ ...formatClasses(Object.values(options.formats ?? {}).flat()),
5463
+ ...formatClasses(options.styleFormats ?? []),
5464
+ ...Array.isArray(options.validClasses) ? options.validClasses : [],
5465
+ ...[...options.tableClassList ?? [], ...options.tableCellClassList ?? []].flatMap(
5466
+ (o) => o.value.split(/\s+/).filter(Boolean)
5467
+ )
5468
+ ]);
5469
+ this.schema = this.buildSchema(
5470
+ syncPlugins,
5471
+ options.validClasses === true ? () => true : (name) => allowedClasses.has(name)
5472
+ );
5473
+ this.formatter = new Formatter(this, allowedClasses);
5474
+ for (const [name, spec] of Object.entries(options.formats ?? {}))
5475
+ this.formatter.register(name, spec);
4670
5476
  syncPlugins.forEach((plugin) => this.registerCommands(plugin));
4671
5477
  const initialDoc = parseContent(this.schema, options.content ?? "");
4672
5478
  const state = EditorState.create({
@@ -4694,11 +5500,12 @@ var Editor = class {
4694
5500
  ]
4695
5501
  });
4696
5502
  this.editable = options.editable ?? true;
5503
+ this.disabled = options.disabled ?? false;
4697
5504
  this.pasteAsText = options.pasteAsText ?? false;
4698
5505
  const handleTransaction = this.handleTransaction.bind(this);
4699
5506
  this.view = new EditorView(contentHost, {
4700
5507
  state,
4701
- editable: () => this.editable,
5508
+ editable: () => this.isEditable(),
4702
5509
  attributes: {
4703
5510
  class: "nova-prosemirror",
4704
5511
  role: "textbox",
@@ -4723,6 +5530,7 @@ var Editor = class {
4723
5530
  }
4724
5531
  });
4725
5532
  this.root.classList.toggle("nova-readonly", !this.editable);
5533
+ this.applyDisabled();
4726
5534
  registerBuiltins(this);
4727
5535
  registerMenuItems(this);
4728
5536
  if (options.slashCommands !== false) registerSlashCommands(this, options.slashCommands ?? []);
@@ -4747,7 +5555,40 @@ var Editor = class {
4747
5555
  if (!this.statusbar) statusbarHost.remove();
4748
5556
  if (options.onChange) this.on("change", options.onChange);
4749
5557
  this.updatePlaceholder();
4750
- this.ready = resolved.loaders.length ? this.loadLazyPlugins(resolved.loaders) : Promise.resolve();
5558
+ const contentCss = this.applyContentStyles();
5559
+ this.ready = Promise.all([
5560
+ resolved.loaders.length ? this.loadLazyPlugins(resolved.loaders) : void 0,
5561
+ contentCss
5562
+ ]).then(() => void 0);
5563
+ }
5564
+ /** contentStyle сразу, contentCss — по мере загрузки. Каждый редактор — своя область. */
5565
+ applyContentStyles() {
5566
+ const { contentStyle, contentCss } = this.options;
5567
+ const files = contentCss === void 0 ? [] : Array.isArray(contentCss) ? contentCss : [contentCss];
5568
+ if (!contentStyle && !files.length) return void 0;
5569
+ const id = `nova-cs-${++contentScopeId}`;
5570
+ this.root.classList.add(id);
5571
+ const scope = `.nova-editor.${id} .nova-prosemirror`;
5572
+ const sheets = files.map(() => "");
5573
+ let detach = null;
5574
+ const apply = () => {
5575
+ if (this.destroyed) return;
5576
+ detach?.();
5577
+ detach = attachCss(this.root, scopeCss([...sheets, contentStyle ?? ""].join("\n"), scope));
5578
+ };
5579
+ this.cleanups.push(() => detach?.());
5580
+ apply();
5581
+ if (!files.length) return void 0;
5582
+ return Promise.all(
5583
+ files.map(
5584
+ (url, index) => loadCss(url).then(
5585
+ (css) => {
5586
+ sheets[index] = css;
5587
+ },
5588
+ (error) => console.warn(`[nova] contentCss: could not load ${url}`, error)
5589
+ )
5590
+ )
5591
+ ).then(apply);
4751
5592
  }
4752
5593
  // ---------- плагины ----------
4753
5594
  /** Разрешён ли контрол/команда/тег по ограничениям контента (без ограничений — всегда да). */
@@ -4761,11 +5602,12 @@ var Editor = class {
4761
5602
  * Схема с узлами и марками плагинов. Конфликт имён — ошибка конфигурации: сообщаем и работаем
4762
5603
  * на базовой схеме, чтобы редактор всё равно открылся.
4763
5604
  */
4764
- buildSchema(plugins) {
5605
+ buildSchema(plugins, classFilter) {
4765
5606
  const nodes = {};
4766
5607
  const marks = {};
4767
5608
  for (const plugin of plugins) {
4768
- for (const [name, spec] of Object.entries(plugin.nodes ?? {})) {
5609
+ const pluginNodes = typeof plugin.nodes === "function" ? plugin.nodes(this) : plugin.nodes;
5610
+ for (const [name, spec] of Object.entries(pluginNodes ?? {})) {
4769
5611
  if (name in nodes) reportPluginError(`Node "${name}" is defined by several plugins`);
4770
5612
  else nodes[name] = spec;
4771
5613
  }
@@ -4775,10 +5617,10 @@ var Editor = class {
4775
5617
  }
4776
5618
  }
4777
5619
  try {
4778
- return createSchema({ nodes, marks });
5620
+ return createSchema({ nodes, marks }, classFilter);
4779
5621
  } catch (error) {
4780
5622
  reportPluginError("Failed to build the document schema from plugins", error);
4781
- return createSchema();
5623
+ return createSchema({}, classFilter);
4782
5624
  }
4783
5625
  }
4784
5626
  collectPmPlugins(plugin) {
@@ -4892,6 +5734,39 @@ var Editor = class {
4892
5734
  if (!addToHistory) tr.setMeta("addToHistory", false);
4893
5735
  this.view.dispatch(tr);
4894
5736
  }
5737
+ /**
5738
+ * Вставить HTML в позицию курсора (как insertContent в TinyMCE). HTML разбирается схемой
5739
+ * редактора — как вставка: без скриптов, опасных ссылок и лишних тегов.
5740
+ * Блоки (абзацы, таблицы) встают отдельными блоками. Таблица, вставляемая при курсоре
5741
+ * внутри таблицы, встаёт после неё (а не заменяет её ячейки).
5742
+ */
5743
+ insertContent(html) {
5744
+ if (!this.isEditable()) return false;
5745
+ const template = document.createElement("template");
5746
+ template.innerHTML = html;
5747
+ const container = document.createElement("div");
5748
+ container.append(template.content);
5749
+ const parser = parserFor(this.schema);
5750
+ const hasBlocks = [...container.children].some((el) => INSERT_BLOCK_TAGS.has(el.tagName));
5751
+ const { state } = this.view;
5752
+ const slice = hasBlocks ? new Slice2(parser.parse(container).content, 0, 0) : parser.parseSlice(container);
5753
+ let hasTable = false;
5754
+ slice.content.descendants((node) => {
5755
+ if (node.type.spec.tableRole === "table") hasTable = true;
5756
+ return !hasTable;
5757
+ });
5758
+ const { $from } = state.selection;
5759
+ let tableDepth = 0;
5760
+ for (let depth = 1; depth <= $from.depth; depth++) {
5761
+ if ($from.node(depth).type.spec.tableRole === "table") {
5762
+ tableDepth = depth;
5763
+ break;
5764
+ }
5765
+ }
5766
+ const tr = hasTable && tableDepth ? state.tr.insert($from.after(tableDepth), slice.content) : state.tr.replaceSelection(slice);
5767
+ this.view.dispatch(tr.scrollIntoView());
5768
+ return true;
5769
+ }
4895
5770
  isEmpty() {
4896
5771
  return this.view.dom.classList.contains("nova-empty");
4897
5772
  }
@@ -4940,8 +5815,32 @@ var Editor = class {
4940
5815
  closeSearch() {
4941
5816
  this.searchBar.close();
4942
5817
  }
5818
+ /** Можно ли сейчас править текст: не «только чтение» и не отключён. */
4943
5819
  isEditable() {
4944
- return this.editable;
5820
+ return this.editable && !this.disabled;
5821
+ }
5822
+ isDisabled() {
5823
+ return this.disabled;
5824
+ }
5825
+ /** Отключить или включить редактор (как disabled у поля формы). */
5826
+ setDisabled(value) {
5827
+ if (this.disabled === value) return;
5828
+ this.disabled = value;
5829
+ this.view.setProps({});
5830
+ this.applyDisabled();
5831
+ if (value) {
5832
+ this.ui.closePopover();
5833
+ this.view.dom.blur();
5834
+ }
5835
+ this.toolbar?.update();
5836
+ this.emit("editableChange");
5837
+ }
5838
+ applyDisabled() {
5839
+ this.root.classList.toggle("nova-disabled", this.disabled);
5840
+ if (this.disabled) this.root.setAttribute("aria-disabled", "true");
5841
+ else this.root.removeAttribute("aria-disabled");
5842
+ if (this.disabled) this.view.dom.setAttribute("tabindex", "-1");
5843
+ else this.view.dom.removeAttribute("tabindex");
4945
5844
  }
4946
5845
  setEditable(value) {
4947
5846
  if (this.editable === value) return;
@@ -5003,6 +5902,7 @@ function createEditor(options) {
5003
5902
  }
5004
5903
 
5005
5904
  export {
5905
+ Formatter,
5006
5906
  en,
5007
5907
  ru,
5008
5908
  registerLanguage,
@@ -5046,4 +5946,4 @@ export {
5046
5946
  parseContent,
5047
5947
  createEditor
5048
5948
  };
5049
- //# sourceMappingURL=chunk-55LD2TT2.js.map
5949
+ //# sourceMappingURL=chunk-46RIM5KP.js.map