@novaprose/tinymce-compat 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1428 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ CompatEditor: () => CompatEditor,
24
+ createTinymce: () => createTinymce,
25
+ mapOptions: () => mapOptions,
26
+ tinymce: () => tinymce
27
+ });
28
+ module.exports = __toCommonJS(src_exports);
29
+ var import_core3 = require("@novaprose/core");
30
+
31
+ // src/editor.ts
32
+ var import_core = require("@novaprose/core");
33
+
34
+ // src/dialog.ts
35
+ var uid = 0;
36
+ var nextId = () => `nova-compat-field-${++uid}`;
37
+ function el(tag, className, text) {
38
+ const node = document.createElement(tag);
39
+ if (className) node.className = className;
40
+ if (text !== void 0) node.textContent = text;
41
+ return node;
42
+ }
43
+ function safeHtml(html) {
44
+ const template = document.createElement("template");
45
+ template.innerHTML = html;
46
+ template.content.querySelectorAll("script, style, iframe, object, embed, link, meta, base, form").forEach((node) => node.remove());
47
+ template.content.querySelectorAll("*").forEach((node) => {
48
+ for (const attr of [...node.attributes]) {
49
+ const value = attr.value.trim().toLowerCase();
50
+ if (attr.name.startsWith("on") || /^(javascript|vbscript|data):/.test(value)) {
51
+ node.removeAttribute(attr.name);
52
+ }
53
+ }
54
+ });
55
+ return template.content;
56
+ }
57
+ function openSpecDialog(editor, spec, reopen) {
58
+ const controls = /* @__PURE__ */ new Map();
59
+ const tabs = /* @__PURE__ */ new Map();
60
+ let currentTab = "";
61
+ let closedByApi = false;
62
+ let handle = null;
63
+ const notifyChange = (name) => spec.onChange?.(api, { name });
64
+ function field(item, input) {
65
+ const id = nextId();
66
+ input.id = id;
67
+ const wrap = el("div", "nova-field");
68
+ if (item.label) {
69
+ const label = el("label", "nova-label", item.label);
70
+ label.htmlFor = id;
71
+ wrap.append(label);
72
+ }
73
+ wrap.append(input);
74
+ return wrap;
75
+ }
76
+ function render(item) {
77
+ const name = item.name ?? "";
78
+ const enabled = item.enabled !== false && item.disabled !== true;
79
+ switch (item.type) {
80
+ case "input":
81
+ case "urlinput":
82
+ case "colorinput": {
83
+ const input = el("input", "nova-input");
84
+ input.type = item.type === "colorinput" ? "color" : item.type === "urlinput" ? "url" : "text";
85
+ if (item.inputMode) input.inputMode = item.inputMode;
86
+ if (item.placeholder) input.placeholder = item.placeholder;
87
+ input.disabled = !enabled;
88
+ input.addEventListener("input", () => notifyChange(name));
89
+ if (name) {
90
+ controls.set(name, {
91
+ // urlinput хранит { value }, остальные — строку.
92
+ get: () => item.type === "urlinput" ? { value: input.value } : input.value,
93
+ set: (value) => {
94
+ input.value = String(
95
+ item.type === "urlinput" && value && typeof value === "object" ? value.value ?? "" : value ?? ""
96
+ );
97
+ },
98
+ focus: () => input.focus(),
99
+ setEnabled: (on) => input.disabled = !on
100
+ });
101
+ }
102
+ return field(item, input);
103
+ }
104
+ case "textarea": {
105
+ const input = el("textarea", "nova-input");
106
+ input.rows = item.maximized ? 10 : 4;
107
+ if (item.placeholder) input.placeholder = item.placeholder;
108
+ input.disabled = !enabled;
109
+ input.addEventListener("input", () => notifyChange(name));
110
+ if (name) {
111
+ controls.set(name, {
112
+ get: () => input.value,
113
+ set: (value) => input.value = String(value ?? ""),
114
+ focus: () => input.focus(),
115
+ setEnabled: (on) => input.disabled = !on
116
+ });
117
+ }
118
+ return field(item, input);
119
+ }
120
+ case "checkbox": {
121
+ const input = el("input", "nova-checkbox");
122
+ input.type = "checkbox";
123
+ input.id = nextId();
124
+ input.disabled = !enabled;
125
+ input.addEventListener("change", () => notifyChange(name));
126
+ const label = el("label", void 0, item.label ?? "");
127
+ label.htmlFor = input.id;
128
+ if (name) {
129
+ controls.set(name, {
130
+ get: () => input.checked,
131
+ set: (value) => input.checked = Boolean(value),
132
+ focus: () => input.focus(),
133
+ setEnabled: (on) => input.disabled = !on
134
+ });
135
+ }
136
+ const wrap = el("div", "nova-field nova-field-inline");
137
+ wrap.append(input, label);
138
+ return wrap;
139
+ }
140
+ case "selectbox":
141
+ case "listbox": {
142
+ const select = el("select", "nova-input nova-select");
143
+ for (const option of item.items ?? []) {
144
+ const node = el("option", void 0, option.text);
145
+ node.value = option.value;
146
+ select.append(node);
147
+ }
148
+ select.disabled = !enabled;
149
+ select.addEventListener("change", () => notifyChange(name));
150
+ if (name) {
151
+ controls.set(name, {
152
+ get: () => select.value,
153
+ set: (value) => select.value = String(value ?? ""),
154
+ focus: () => select.focus(),
155
+ setEnabled: (on) => select.disabled = !on
156
+ });
157
+ }
158
+ return field(item, select);
159
+ }
160
+ case "button": {
161
+ const button = el(
162
+ "button",
163
+ item.primary || item.buttonType === "primary" ? "nova-button nova-button-primary" : "nova-button",
164
+ item.text ?? ""
165
+ );
166
+ button.type = "button";
167
+ button.disabled = !enabled;
168
+ button.addEventListener("click", () => spec.onAction?.(api, { name }));
169
+ if (name) {
170
+ controls.set(name, {
171
+ get: () => void 0,
172
+ set: () => {
173
+ },
174
+ focus: () => button.focus(),
175
+ setEnabled: (on) => button.disabled = !on
176
+ });
177
+ }
178
+ return button;
179
+ }
180
+ case "htmlpanel": {
181
+ const panel = el("div", "nova-compat-html");
182
+ panel.append(safeHtml(item.html ?? ""));
183
+ return panel;
184
+ }
185
+ case "alertbanner": {
186
+ const banner = el("p", `nova-compat-alert is-${item.level ?? "info"}`, item.text ?? "");
187
+ banner.setAttribute("role", item.level === "error" ? "alert" : "status");
188
+ return banner;
189
+ }
190
+ case "label": {
191
+ const group = el("div", "nova-compat-group");
192
+ group.append(el("p", "nova-label", item.label ?? ""));
193
+ for (const child of item.items ?? []) {
194
+ const node = render(child);
195
+ if (node) group.append(node);
196
+ }
197
+ return group;
198
+ }
199
+ case "grid":
200
+ case "bar": {
201
+ const grid = el("div", "nova-compat-grid");
202
+ const columns = item.type === "bar" ? item.items?.length ?? 1 : item.columns === "auto" ? 2 : item.columns ?? 2;
203
+ grid.style.gridTemplateColumns = `repeat(${Number(columns) || 2}, minmax(0, 1fr))`;
204
+ for (const child of item.items ?? []) {
205
+ const node = render(child);
206
+ if (node) grid.append(node);
207
+ }
208
+ return grid;
209
+ }
210
+ default:
211
+ console.warn(`[nova] tinymce-compat: dialog component "${item.type}" is not supported yet`);
212
+ return null;
213
+ }
214
+ }
215
+ const body = el("div", "nova-compat-dialog nova-form");
216
+ if (spec.body.type === "tabpanel") {
217
+ const tabList = el("div", "nova-compat-tabs");
218
+ tabList.setAttribute("role", "tablist");
219
+ body.append(tabList);
220
+ spec.body.tabs.forEach((tab, index) => {
221
+ const name = tab.name ?? tab.title;
222
+ const button = el("button", "nova-compat-tab", tab.title);
223
+ button.type = "button";
224
+ button.setAttribute("role", "tab");
225
+ const panel = el("div", "nova-compat-tabpanel");
226
+ panel.setAttribute("role", "tabpanel");
227
+ for (const item of tab.items) {
228
+ const node = render(item);
229
+ if (node) panel.append(node);
230
+ }
231
+ button.addEventListener("click", () => api.showTab(name));
232
+ tabs.set(name, { button, panel });
233
+ tabList.append(button);
234
+ body.append(panel);
235
+ if (index === 0) currentTab = name;
236
+ });
237
+ } else {
238
+ for (const item of spec.body.items) {
239
+ const node = render(item);
240
+ if (node) body.append(node);
241
+ }
242
+ }
243
+ const buttons = spec.buttons ?? [];
244
+ const submit = buttons.find((b) => b.type === "submit");
245
+ const custom = buttons.filter((b) => b.type === "custom");
246
+ if (custom.length) {
247
+ const row = el("div", "nova-compat-actions");
248
+ for (const b of custom) {
249
+ const button = el(
250
+ "button",
251
+ b.primary ? "nova-button nova-button-primary" : "nova-button",
252
+ b.text
253
+ );
254
+ button.type = "button";
255
+ button.disabled = b.enabled === false;
256
+ button.addEventListener("click", () => spec.onAction?.(api, { name: b.name ?? b.text }));
257
+ if (b.name) {
258
+ controls.set(b.name, {
259
+ get: () => void 0,
260
+ set: () => {
261
+ },
262
+ focus: () => button.focus(),
263
+ setEnabled: (on) => button.disabled = !on
264
+ });
265
+ }
266
+ row.append(button);
267
+ }
268
+ body.append(row);
269
+ }
270
+ const api = {
271
+ getData: () => {
272
+ const data = {};
273
+ controls.forEach((control, name) => {
274
+ const value = control.get();
275
+ if (value !== void 0) data[name] = value;
276
+ });
277
+ return data;
278
+ },
279
+ setData: (data) => {
280
+ for (const [name, value] of Object.entries(data)) controls.get(name)?.set(value);
281
+ },
282
+ close: () => {
283
+ closedByApi = true;
284
+ handle?.close();
285
+ },
286
+ block: () => handle?.setBusy(true),
287
+ unblock: () => handle?.setBusy(false),
288
+ focus: (name) => controls.get(name)?.focus(),
289
+ disable: (name) => controls.get(name)?.setEnabled(false),
290
+ enable: (name) => controls.get(name)?.setEnabled(true),
291
+ showTab: (name) => {
292
+ if (!tabs.has(name)) return;
293
+ const old = currentTab;
294
+ currentTab = name;
295
+ tabs.forEach(({ button, panel }, key) => {
296
+ const on = key === name;
297
+ button.setAttribute("aria-selected", String(on));
298
+ button.tabIndex = on ? 0 : -1;
299
+ panel.hidden = !on;
300
+ });
301
+ if (old && old !== name) spec.onTabChange?.(api, { newTabName: name, oldTabName: old });
302
+ },
303
+ redial: (next) => {
304
+ api.close();
305
+ Object.assign(api, reopen(next));
306
+ }
307
+ };
308
+ if (spec.initialData) api.setData(spec.initialData);
309
+ if (currentTab) api.showTab(currentTab);
310
+ handle = editor.ui.openDialog({
311
+ title: spec.title,
312
+ body,
313
+ ...submit ? { submitLabel: submit.text } : {},
314
+ ...spec.size === "large" ? { size: "large" } : {},
315
+ onSubmit: () => {
316
+ spec.onSubmit?.(api);
317
+ return closedByApi;
318
+ },
319
+ onClose: () => {
320
+ if (!closedByApi) spec.onCancel?.(api);
321
+ spec.onClose?.();
322
+ }
323
+ });
324
+ return api;
325
+ }
326
+
327
+ // src/editor.ts
328
+ var import_prosemirror_model = require("prosemirror-model");
329
+ var import_prosemirror_state = require("prosemirror-state");
330
+ var serializer = new import_core.HTMLSerializer();
331
+ var BLOCK_TAGS = /* @__PURE__ */ new Set([
332
+ "P",
333
+ "H1",
334
+ "H2",
335
+ "H3",
336
+ "H4",
337
+ "H5",
338
+ "H6",
339
+ "UL",
340
+ "OL",
341
+ "TABLE",
342
+ "BLOCKQUOTE",
343
+ "PRE",
344
+ "HR",
345
+ "DIV",
346
+ "FIGURE"
347
+ ]);
348
+ var COMMANDS = {
349
+ bold: "bold",
350
+ italic: "italic",
351
+ underline: "underline",
352
+ strikethrough: "strike",
353
+ superscript: "superscript",
354
+ subscript: "subscript",
355
+ justifyleft: "alignLeft",
356
+ justifycenter: "alignCenter",
357
+ justifyright: "alignRight",
358
+ justifyfull: "alignJustify",
359
+ insertunorderedlist: "bulletList",
360
+ insertorderedlist: "orderedList",
361
+ indent: "indent",
362
+ outdent: "outdent",
363
+ undo: "undo",
364
+ redo: "redo",
365
+ removeformat: "clearFormatting",
366
+ unlink: "unlink",
367
+ inserthorizontalrule: "horizontalRule",
368
+ mceblockquote: "blockquote"
369
+ };
370
+ var FORMAT_BLOCKS = {
371
+ p: "paragraph",
372
+ h1: "h1",
373
+ h2: "h2",
374
+ h3: "h3",
375
+ h4: "h4",
376
+ h5: "h5",
377
+ h6: "h6",
378
+ blockquote: "blockquote",
379
+ pre: "codeBlock"
380
+ };
381
+ var ICON_NAMES = {
382
+ bold: "bold",
383
+ italic: "italic",
384
+ underline: "underline",
385
+ "strike-through": "strike",
386
+ link: "link",
387
+ unlink: "unlink",
388
+ image: "image",
389
+ table: "table",
390
+ undo: "undo",
391
+ redo: "redo",
392
+ "align-left": "alignLeft",
393
+ "align-center": "alignCenter",
394
+ "align-right": "alignRight",
395
+ "align-justify": "alignJustify",
396
+ "unordered-list": "bulletList",
397
+ "ordered-list": "orderedList",
398
+ indent: "indent",
399
+ outdent: "outdent",
400
+ quote: "blockquote",
401
+ "code-sample": "codeBlock",
402
+ "horizontal-rule": "horizontalRule",
403
+ "remove-formatting": "clearFormatting",
404
+ fullscreen: "fullscreen",
405
+ preview: "preview",
406
+ sourcecode: "sourceCode",
407
+ help: "help",
408
+ print: "print",
409
+ search: "search",
410
+ copy: "copy",
411
+ "edit-block": "edit",
412
+ checkmark: "check",
413
+ close: "close",
414
+ upload: "upload",
415
+ subscript: "subscript",
416
+ superscript: "superscript",
417
+ "paste-text": "pasteText",
418
+ "text-color": "textColor",
419
+ "highlight-bg-color": "highlight",
420
+ "line-height": "lineHeight"
421
+ };
422
+ var FORMAT_COMMANDS = {
423
+ bold: "bold",
424
+ italic: "italic",
425
+ underline: "underline",
426
+ strikethrough: "strike",
427
+ superscript: "superscript",
428
+ subscript: "subscript",
429
+ code: "code",
430
+ p: "paragraph",
431
+ h1: "h1",
432
+ h2: "h2",
433
+ h3: "h3",
434
+ h4: "h4",
435
+ h5: "h5",
436
+ h6: "h6",
437
+ blockquote: "blockquote",
438
+ pre: "codeBlock",
439
+ alignleft: "alignLeft",
440
+ aligncenter: "alignCenter",
441
+ alignright: "alignRight",
442
+ alignjustify: "alignJustify"
443
+ };
444
+ var TAG_FORMATS = /* @__PURE__ */ new Set(["p", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "pre"]);
445
+ var BLOCK_FORMATS = /* @__PURE__ */ new Set([
446
+ "p",
447
+ "h1",
448
+ "h2",
449
+ "h3",
450
+ "h4",
451
+ "h5",
452
+ "h6",
453
+ "blockquote",
454
+ "pre",
455
+ "alignleft",
456
+ "aligncenter",
457
+ "alignright",
458
+ "alignjustify"
459
+ ]);
460
+ var STYLE_FORMATS = {
461
+ forecolor: "color",
462
+ hilitecolor: "background",
463
+ fontname: "font_family",
464
+ fontsize: "font_size"
465
+ };
466
+ function warnDom(method) {
467
+ console.warn(
468
+ `[nova] tinymce-compat: editor.dom.${method} changes the editor DOM directly, which NovaProse redraws from its document model. Use setContent, insertContent or editor.formatter instead.`
469
+ );
470
+ }
471
+ var customIcons = /* @__PURE__ */ new Map();
472
+ function resolveIcon(name) {
473
+ if (typeof name !== "string" || !name) return void 0;
474
+ if (customIcons.has(name)) return customIcons.get(name);
475
+ const own = ICON_NAMES[name] ?? (name in import_core.icons ? name : void 0);
476
+ return own ? import_core.icons[own] : void 0;
477
+ }
478
+ function buttonApi(compat) {
479
+ let active = false;
480
+ let enabled = true;
481
+ return {
482
+ state: {
483
+ get active() {
484
+ return active;
485
+ },
486
+ get enabled() {
487
+ return enabled;
488
+ }
489
+ },
490
+ api: {
491
+ isActive: () => active,
492
+ setActive: (value) => {
493
+ active = value;
494
+ compat.core.updateUI();
495
+ },
496
+ isEnabled: () => enabled,
497
+ setEnabled: (value) => {
498
+ enabled = value;
499
+ compat.core.updateUI();
500
+ },
501
+ // Совместимость со старыми версиями API.
502
+ isDisabled: () => !enabled,
503
+ setDisabled: (value) => {
504
+ enabled = !value;
505
+ compat.core.updateUI();
506
+ }
507
+ }
508
+ };
509
+ }
510
+ var CompatEditor = class {
511
+ id;
512
+ core;
513
+ targetElm;
514
+ settings;
515
+ initialized = false;
516
+ removed = false;
517
+ handlers = /* @__PURE__ */ new Map();
518
+ dirty = false;
519
+ teardowns = [];
520
+ constructor(core, target, id, settings) {
521
+ this.core = core;
522
+ this.targetElm = target;
523
+ this.id = id;
524
+ this.settings = settings;
525
+ }
526
+ // ---------- содержимое ----------
527
+ getContent(args = {}) {
528
+ const event = { format: args.format ?? "html", content: "" };
529
+ event.content = event.format === "text" ? this.core.getText() : this.core.getHTML();
530
+ this.fire("GetContent", event);
531
+ return event.content;
532
+ }
533
+ setContent(content, args = {}) {
534
+ const event = { content, ...args };
535
+ this.fire("BeforeSetContent", event);
536
+ this.core.setContent(event.content);
537
+ this.fire("SetContent", event);
538
+ return event.content;
539
+ }
540
+ /**
541
+ * Вставить HTML на место выделения. Блоки (<p>, списки, таблицы) — отдельными блоками (абзац
542
+ * разрезается), строчное содержимое — в текущую строку. Разбор — схемой редактора: те же проверки
543
+ * ссылок и разметки, что при загрузке содержимого.
544
+ */
545
+ insertContent(content) {
546
+ const template = document.createElement("template");
547
+ template.innerHTML = content;
548
+ const container = document.createElement("div");
549
+ container.append(template.content);
550
+ const parser = (0, import_core.parserFor)(this.core.schema);
551
+ const hasBlocks = [...container.children].some((el2) => BLOCK_TAGS.has(el2.tagName));
552
+ const slice = hasBlocks ? new import_prosemirror_model.Slice(parser.parse(container).content, 0, 0) : parser.parseSlice(container);
553
+ const { state, dispatch } = this.core.view;
554
+ dispatch(state.tr.replaceSelection(slice).scrollIntoView());
555
+ }
556
+ resetContent(content) {
557
+ this.core.setContent(content ?? this.settings.__initialContent ?? "", {
558
+ addToHistory: false
559
+ });
560
+ this.setDirty(false);
561
+ }
562
+ getBody() {
563
+ return this.core.view.dom;
564
+ }
565
+ getElement() {
566
+ return this.targetElm;
567
+ }
568
+ getContainer() {
569
+ return this.core.root;
570
+ }
571
+ getContentAreaContainer() {
572
+ return this.core.view.dom.parentElement ?? this.core.root;
573
+ }
574
+ getDoc() {
575
+ return this.core.root.ownerDocument;
576
+ }
577
+ getWin() {
578
+ return this.core.root.ownerDocument.defaultView;
579
+ }
580
+ // ---------- команды ----------
581
+ execCommand(command, _ui, value) {
582
+ const name = command.toLowerCase();
583
+ let done = false;
584
+ if (COMMANDS[name]) done = this.core.exec(COMMANDS[name]);
585
+ else if (name === "formatblock" || name === "mcetoggleformat") {
586
+ const block = FORMAT_BLOCKS[String(value ?? "").toLowerCase()];
587
+ done = block ? this.core.exec(block) : false;
588
+ } else if (name === "mceinsertcontent" || name === "inserthtml") {
589
+ this.insertContent(String(value ?? ""));
590
+ done = true;
591
+ } else if (name === "mcesetcontent") {
592
+ this.setContent(String(value ?? ""));
593
+ done = true;
594
+ } else if (name === "selectall") {
595
+ const { state, dispatch } = this.core.view;
596
+ dispatch(state.tr.setSelection(new import_prosemirror_state.AllSelection(state.doc)));
597
+ done = true;
598
+ } else if (name === "mcecleanup") {
599
+ done = true;
600
+ } else {
601
+ const custom = this.commands.get(name);
602
+ if (custom) {
603
+ custom(_ui, value);
604
+ done = true;
605
+ }
606
+ }
607
+ if (done) this.fire("ExecCommand", { command, ui: _ui, value });
608
+ return done;
609
+ }
610
+ queryCommandState(command) {
611
+ const name = COMMANDS[command.toLowerCase()];
612
+ return name ? this.core.isActive(name) : false;
613
+ }
614
+ queryCommandSupported(command) {
615
+ const name = command.toLowerCase();
616
+ return name in COMMANDS || ["formatblock", "mceinsertcontent", "mcesetcontent"].includes(name) || this.commands.has(name);
617
+ }
618
+ commands = /* @__PURE__ */ new Map();
619
+ addCommand(name, callback) {
620
+ this.commands.set(name.toLowerCase(), callback);
621
+ }
622
+ // ---------- события ----------
623
+ on(names, handler, prepend = false) {
624
+ for (const name of names.toLowerCase().split(/\s+/).filter(Boolean)) {
625
+ const set = this.handlers.get(name) ?? /* @__PURE__ */ new Set();
626
+ if (prepend) this.handlers.set(name, /* @__PURE__ */ new Set([handler, ...set]));
627
+ else this.handlers.set(name, set.add(handler));
628
+ }
629
+ return this;
630
+ }
631
+ off(names, handler) {
632
+ if (!names) {
633
+ this.handlers.clear();
634
+ return this;
635
+ }
636
+ for (const name of names.toLowerCase().split(/\s+/).filter(Boolean)) {
637
+ if (handler) this.handlers.get(name)?.delete(handler);
638
+ else this.handlers.delete(name);
639
+ }
640
+ return this;
641
+ }
642
+ once(names, handler) {
643
+ const wrapped = (event) => {
644
+ this.off(names, wrapped);
645
+ return handler(event);
646
+ };
647
+ return this.on(names, wrapped);
648
+ }
649
+ fire(name, event = {}) {
650
+ const payload = Object.assign(event, { type: name.toLowerCase(), target: this });
651
+ for (const handler of [...this.handlers.get(name.toLowerCase()) ?? []]) {
652
+ try {
653
+ handler(payload);
654
+ } catch (error) {
655
+ console.error(`[nova] tinymce-compat: "${name}" handler failed`, error);
656
+ }
657
+ }
658
+ return payload;
659
+ }
660
+ /** DOM-событие текста (keydown, click…) — обработчикам передаётся само событие браузера. */
661
+ fireNative(name, event) {
662
+ for (const handler of [...this.handlers.get(name) ?? []]) {
663
+ try {
664
+ handler(event);
665
+ } catch (error) {
666
+ console.error(`[nova] tinymce-compat: "${name}" handler failed`, error);
667
+ }
668
+ }
669
+ }
670
+ /** Иконка для кнопок по имени (tinymce.IconManager / editor.ui.registry.addIcon). */
671
+ static registerIcon(name, svg) {
672
+ customIcons.set(name, svg);
673
+ }
674
+ /** Новое имя fire в последних версиях API. */
675
+ dispatch(name, event) {
676
+ return this.fire(name, event);
677
+ }
678
+ hasEventListeners(name) {
679
+ return (this.handlers.get(name.toLowerCase())?.size ?? 0) > 0;
680
+ }
681
+ // ---------- состояние ----------
682
+ isDirty() {
683
+ return this.dirty;
684
+ }
685
+ setDirty(state) {
686
+ const changed = this.dirty !== state;
687
+ this.dirty = state;
688
+ if (changed && state) this.fire("Dirty");
689
+ }
690
+ /** Записать содержимое в исходный <textarea> (как при отправке формы). */
691
+ save() {
692
+ const content = this.getContent();
693
+ const event = this.fire("SaveContent", { content });
694
+ if (this.targetElm instanceof HTMLTextAreaElement) {
695
+ this.targetElm.value = String(event.content);
696
+ }
697
+ this.setDirty(false);
698
+ return String(event.content);
699
+ }
700
+ focus() {
701
+ this.core.focus();
702
+ }
703
+ hasFocus() {
704
+ return this.core.view.hasFocus();
705
+ }
706
+ hide() {
707
+ this.core.root.hidden = true;
708
+ if (this.targetElm instanceof HTMLTextAreaElement) this.targetElm.hidden = false;
709
+ }
710
+ show() {
711
+ this.core.root.hidden = false;
712
+ if (this.targetElm instanceof HTMLTextAreaElement) this.targetElm.hidden = true;
713
+ }
714
+ isHidden() {
715
+ return this.core.root.hidden === true;
716
+ }
717
+ getParam(name, defaultValue) {
718
+ return name in this.settings ? this.settings[name] : defaultValue;
719
+ }
720
+ options = {
721
+ get: (name) => this.settings[name],
722
+ set: (name, value) => {
723
+ this.settings[name] = value;
724
+ return true;
725
+ },
726
+ isSet: (name) => name in this.settings,
727
+ isRegistered: () => true,
728
+ register: () => {
729
+ }
730
+ };
731
+ mode = {
732
+ get: () => this.core.isEditable() ? "design" : "readonly",
733
+ set: (mode) => this.core.setEditable(mode !== "readonly"),
734
+ isReadOnly: () => !this.core.isEditable()
735
+ };
736
+ undoManager = {
737
+ undo: () => this.core.exec("undo"),
738
+ redo: () => this.core.exec("redo"),
739
+ hasUndo: () => this.core.can("undo"),
740
+ hasRedo: () => this.core.can("redo"),
741
+ add: () => null,
742
+ clear: () => {
743
+ },
744
+ transact: (callback) => {
745
+ callback();
746
+ return null;
747
+ },
748
+ ignore: (callback) => callback()
749
+ };
750
+ selection = {
751
+ getContent: (args = {}) => {
752
+ const { state } = this.core.view;
753
+ const { from, to } = state.selection;
754
+ if (args.format === "text") return state.doc.textBetween(from, to, "\n");
755
+ return serializer.serializeFragment(state.selection.content().content);
756
+ },
757
+ setContent: (content) => this.insertContent(content),
758
+ getNode: () => {
759
+ const { from } = this.core.view.state.selection;
760
+ const { node } = this.core.view.domAtPos(from);
761
+ return node instanceof Element ? node : node.parentElement;
762
+ },
763
+ getStart: () => this.selection.getNode(),
764
+ getEnd: () => this.selection.getNode(),
765
+ isCollapsed: () => this.core.view.state.selection.empty,
766
+ collapse: (toStart = false) => {
767
+ const { state, dispatch } = this.core.view;
768
+ const pos = toStart ? state.selection.from : state.selection.to;
769
+ dispatch(state.tr.setSelection(import_prosemirror_state.TextSelection.near(state.doc.resolve(pos))));
770
+ }
771
+ };
772
+ notificationManager = {
773
+ open: (args) => this.core.ui.notify({
774
+ text: args.text,
775
+ ...args.type ? { type: args.type } : {},
776
+ ...args.timeout !== void 0 ? { timeout: args.timeout } : {}
777
+ }),
778
+ close: () => {
779
+ }
780
+ };
781
+ windowManager = {
782
+ alert: (message, callback) => {
783
+ const p = document.createElement("p");
784
+ p.textContent = message;
785
+ this.core.ui.openDialog({
786
+ title: "",
787
+ body: p,
788
+ onSubmit: () => true,
789
+ ...callback ? { onClose: callback } : {}
790
+ });
791
+ },
792
+ confirm: (message, callback) => {
793
+ const p = document.createElement("p");
794
+ p.textContent = message;
795
+ let confirmed = false;
796
+ this.core.ui.openDialog({
797
+ title: "",
798
+ body: p,
799
+ submitLabel: "OK",
800
+ onSubmit: () => {
801
+ confirmed = true;
802
+ return true;
803
+ },
804
+ onClose: () => callback?.(confirmed)
805
+ });
806
+ },
807
+ open: (spec) => openSpecDialog(this.core, spec, (next) => this.windowManager.open(next))
808
+ };
809
+ /** editor.ui.registry — кнопки и пункты меню в формате TinyMCE поверх реестра NovaProse. */
810
+ ui = {
811
+ registry: {
812
+ addIcon: (name, svg) => {
813
+ customIcons.set(name, svg);
814
+ },
815
+ addButton: (name, spec) => this.addButton(name, spec, false),
816
+ addToggleButton: (name, spec) => this.addButton(name, spec, true),
817
+ addMenuButton: (name, spec) => {
818
+ let items = [];
819
+ spec.fetch((result) => items = result);
820
+ const icon = resolveIcon(spec.icon);
821
+ this.core.ui.registry.addMenuButton(name, {
822
+ tooltip: spec.tooltip ?? spec.text ?? name,
823
+ ...icon ? { icon } : { text: spec.text ?? name },
824
+ items: () => {
825
+ spec.fetch((result) => items = result);
826
+ return items.map(
827
+ (item, index) => item.type === "separator" ? { type: "separator" } : {
828
+ id: `${name}-${index}`,
829
+ label: item.text ?? "",
830
+ onSelect: () => item.onAction?.({})
831
+ }
832
+ );
833
+ }
834
+ });
835
+ },
836
+ addMenuItem: (name, spec) => {
837
+ const icon = resolveIcon(spec.icon);
838
+ this.core.ui.registry.addMenuItem(name, {
839
+ text: spec.text ?? name,
840
+ ...icon ? { icon } : {},
841
+ onAction: () => spec.onAction?.({})
842
+ });
843
+ },
844
+ /**
845
+ * Контекстная панель: predicate(node) получает элемент под курсором, items — кнопки тулбара.
846
+ * position: 'node' (над элементом) или 'selection'/'line' (у выделения).
847
+ */
848
+ addContextToolbar: (name, spec) => {
849
+ this.core.ui.registry.addContextToolbar(name, {
850
+ label: spec.label ?? name,
851
+ items: spec.items,
852
+ position: spec.position === "node" ? "node" : "selection",
853
+ predicate: () => {
854
+ const node = this.selection.getNode();
855
+ return !!node && this.getBody().contains(node) && spec.predicate(node);
856
+ }
857
+ });
858
+ },
859
+ addContextForm: () => {
860
+ console.warn("[nova] tinymce-compat: addContextForm is not supported yet");
861
+ },
862
+ getAll: () => ({})
863
+ }
864
+ };
865
+ addButton(name, spec, toggle) {
866
+ const { api, state } = buttonApi(this);
867
+ if (spec.enabled === false) api.setEnabled(false);
868
+ if (spec.active) api.setActive(true);
869
+ const icon = resolveIcon(spec.icon);
870
+ this.core.ui.registry.addButton(name, {
871
+ tooltip: spec.tooltip ?? spec.text ?? name,
872
+ ...icon ? { icon } : { text: spec.text ?? name },
873
+ isEnabled: () => state.enabled,
874
+ ...toggle ? { isActive: () => state.active } : {},
875
+ onAction: () => spec.onAction?.(api)
876
+ });
877
+ if (spec.onSetup) {
878
+ const run = () => {
879
+ const teardown = spec.onSetup(api);
880
+ if (typeof teardown === "function") this.teardowns.push(teardown);
881
+ };
882
+ if (this.initialized) run();
883
+ else this.once("init", run);
884
+ }
885
+ }
886
+ /**
887
+ * editor.dom — то, что имеет смысл поверх модели документа: поиск и чтение. Менять DOM текста
888
+ * напрямую нельзя (редактор перерисует его из модели) — для правок есть setContent/insertContent/
889
+ * formatter; такие вызовы пишут предупреждение.
890
+ */
891
+ dom = {
892
+ select: (selector, scope) => [
893
+ ...(scope ?? this.getBody()).querySelectorAll(selector)
894
+ ],
895
+ get: (id) => typeof id === "string" ? this.getBody().querySelector(`#${CSS.escape(id)}`) : id,
896
+ getParent: (node, selector) => {
897
+ let current = node instanceof Element ? node : node?.parentElement ?? null;
898
+ while (current && current !== this.getBody()) {
899
+ if (typeof selector === "string" ? current.matches(selector) : selector(current))
900
+ return current;
901
+ current = current.parentElement;
902
+ }
903
+ return null;
904
+ },
905
+ getParents: (node, selector) => {
906
+ const result = [];
907
+ let current = node instanceof Element ? node : node?.parentElement ?? null;
908
+ while (current && current !== this.getBody()) {
909
+ if (!selector || current.matches(selector)) result.push(current);
910
+ current = current.parentElement;
911
+ }
912
+ return result;
913
+ },
914
+ is: (node, selector) => !!node?.matches(selector),
915
+ getAttrib: (node, name, fallback = "") => node?.getAttribute(name) ?? fallback,
916
+ hasClass: (node, name) => !!node?.classList.contains(name),
917
+ getStyle: (node, name) => node instanceof HTMLElement ? node.style.getPropertyValue(name) : "",
918
+ getRoot: () => this.getBody(),
919
+ encode: (text) => text.replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`),
920
+ decode: (html) => {
921
+ const textarea = document.createElement("textarea");
922
+ textarea.innerHTML = html;
923
+ return textarea.value;
924
+ },
925
+ /** Новый (не вставленный) элемент: атрибуты — через setAttribute, содержимое — текстом. */
926
+ create: (tag, attrs = {}, text) => {
927
+ const node = document.createElement(tag);
928
+ for (const [name, value] of Object.entries(attrs)) {
929
+ if (!name.startsWith("on")) node.setAttribute(name, value);
930
+ }
931
+ if (text !== void 0) node.textContent = text;
932
+ return node;
933
+ },
934
+ uniqueId: (prefix = "mce_") => `${prefix}${Math.random().toString(36).slice(2, 10)}`,
935
+ setAttrib: () => warnDom("setAttrib"),
936
+ addClass: () => warnDom("addClass"),
937
+ removeClass: () => warnDom("removeClass"),
938
+ setStyle: () => warnDom("setStyle"),
939
+ remove: () => warnDom("remove")
940
+ };
941
+ /**
942
+ * editor.formatter — встроенные форматы TinyMCE: apply/remove/toggle/match.
943
+ * Свои форматы (register) пока не поддержаны.
944
+ */
945
+ formatter = {
946
+ apply: (name, vars = {}) => this.applyFormat(name, vars, "apply"),
947
+ remove: (name) => this.applyFormat(name, {}, "remove"),
948
+ toggle: (name, vars = {}) => this.applyFormat(name, vars, this.formatter.match(name) ? "remove" : "apply"),
949
+ match: (name) => {
950
+ const key = name.toLowerCase();
951
+ if (TAG_FORMATS.has(key)) return this.blockMatches(key);
952
+ const command = FORMAT_COMMANDS[key];
953
+ if (command) return this.core.isActive(command);
954
+ const style = STYLE_FORMATS[key];
955
+ if (!style) return false;
956
+ const { state } = this.core.view;
957
+ const { from, to, empty } = state.selection;
958
+ const type = state.schema.marks[style];
959
+ return empty || !type ? (0, import_core.getStyle)(state, style) !== null : state.doc.rangeHasMark(from, to, type);
960
+ },
961
+ canApply: (name) => name.toLowerCase() in FORMAT_COMMANDS || name.toLowerCase() in STYLE_FORMATS,
962
+ register: (name) => {
963
+ console.warn(`[nova] tinymce-compat: formatter.register("${name}") is not supported yet`);
964
+ }
965
+ };
966
+ blockMatches(key) {
967
+ const { $from } = this.core.view.state.selection;
968
+ for (let depth = $from.depth; depth > 0; depth -= 1) {
969
+ const node = $from.node(depth);
970
+ const name = node.type.name;
971
+ if (key === "blockquote" && name === "blockquote") return true;
972
+ if (depth !== $from.depth) continue;
973
+ if (key === "p") return name === "paragraph";
974
+ if (key === "pre") return name === "code_block";
975
+ if (/^h[1-6]$/.test(key)) return name === "heading" && node.attrs.level === Number(key[1]);
976
+ }
977
+ let first = null;
978
+ this.core.view.state.doc.descendants((node) => {
979
+ if (first || !node.isTextblock) return !first;
980
+ first = { name: node.type.name, level: node.attrs.level };
981
+ return false;
982
+ });
983
+ if (!$from.depth && first) {
984
+ const block = first;
985
+ if (key === "p") return block.name === "paragraph";
986
+ if (key === "pre") return block.name === "code_block";
987
+ if (/^h[1-6]$/.test(key)) return block.name === "heading" && block.level === Number(key[1]);
988
+ }
989
+ return false;
990
+ }
991
+ applyFormat(name, vars, action) {
992
+ const key = name.toLowerCase();
993
+ const command = FORMAT_COMMANDS[key];
994
+ if (command) {
995
+ const active = this.formatter.match(key);
996
+ if (BLOCK_FORMATS.has(key)) {
997
+ if (action === "apply") this.core.exec(command);
998
+ else if (active) this.core.exec("paragraph");
999
+ } else if (action === "apply" !== active) {
1000
+ this.core.exec(command);
1001
+ }
1002
+ return;
1003
+ }
1004
+ const style = STYLE_FORMATS[key];
1005
+ if (style) {
1006
+ this.core.exec((0, import_core.setStyle)(style, action === "apply" ? vars.value ?? null : null));
1007
+ return;
1008
+ }
1009
+ console.warn(`[nova] tinymce-compat: format "${name}" is not supported yet`);
1010
+ }
1011
+ /** Убрать редактор и вернуть исходный элемент (как editor.remove()). */
1012
+ remove() {
1013
+ if (this.removed) return;
1014
+ this.fire("remove");
1015
+ this.save();
1016
+ this.teardowns.splice(0).forEach((teardown) => teardown());
1017
+ this.removed = true;
1018
+ this.core.destroy();
1019
+ this.core.root.remove();
1020
+ const wrapper = this.settings.__wrapper;
1021
+ wrapper?.remove();
1022
+ this.targetElm.hidden = false;
1023
+ this.off();
1024
+ }
1025
+ destroy() {
1026
+ this.remove();
1027
+ }
1028
+ };
1029
+
1030
+ // src/options.ts
1031
+ var import_core2 = require("@novaprose/core");
1032
+ var BUILT_IN = /* @__PURE__ */ new Set([
1033
+ "lists",
1034
+ "link",
1035
+ "image",
1036
+ "table",
1037
+ "code",
1038
+ "codesample",
1039
+ "preview",
1040
+ "searchreplace",
1041
+ "fullscreen",
1042
+ "help",
1043
+ "wordcount",
1044
+ "paste",
1045
+ "hr",
1046
+ "print",
1047
+ "textcolor",
1048
+ "colorpicker",
1049
+ "contextmenu",
1050
+ "tabfocus",
1051
+ "textpattern",
1052
+ "imagetools",
1053
+ "powerpaste",
1054
+ "importcss",
1055
+ "accordion"
1056
+ ]);
1057
+ var RENAMED = {
1058
+ tinycomments: "comments"
1059
+ };
1060
+ var IGNORED = /* @__PURE__ */ new Set([
1061
+ "selector",
1062
+ "target",
1063
+ "license_key",
1064
+ "api_key",
1065
+ "branding",
1066
+ "promotion",
1067
+ "skin",
1068
+ "skin_url",
1069
+ "content_css",
1070
+ "icons",
1071
+ "icons_url",
1072
+ "theme",
1073
+ "theme_url",
1074
+ "base_url",
1075
+ "suffix",
1076
+ "referrer_policy",
1077
+ "convert_urls",
1078
+ "relative_urls",
1079
+ "remove_script_host",
1080
+ "document_base_url",
1081
+ "entity_encoding",
1082
+ "height",
1083
+ "min_height",
1084
+ "max_height",
1085
+ "width",
1086
+ "resize",
1087
+ "content_style",
1088
+ "setup",
1089
+ "init_instance_callback",
1090
+ "inline",
1091
+ "plugins",
1092
+ "toolbar",
1093
+ "menubar",
1094
+ "statusbar",
1095
+ "placeholder",
1096
+ "readonly",
1097
+ "language",
1098
+ "images_upload_handler",
1099
+ "paste_as_text",
1100
+ "paste_preprocess",
1101
+ "paste_postprocess",
1102
+ "invalid_elements",
1103
+ "valid_elements",
1104
+ "valid_styles",
1105
+ "toolbar_mode",
1106
+ "toolbar_sticky",
1107
+ "font_family_formats",
1108
+ "font_size_formats",
1109
+ "line_height_formats",
1110
+ "color_map",
1111
+ "autosave_interval",
1112
+ "autosave_retention",
1113
+ "autosave_prefix",
1114
+ "quickbars_selection_toolbar",
1115
+ "quickbars_insert_toolbar",
1116
+ "mentions_fetch",
1117
+ "tinycomments_author",
1118
+ "tinycomments_author_name"
1119
+ ]);
1120
+ var list = (value) => (Array.isArray(value) ? value.join(" ") : String(value ?? "")).split(/[\s,]+/).filter(Boolean);
1121
+ function parseFormats(value) {
1122
+ if (typeof value !== "string") return void 0;
1123
+ return value.split(";").map((item) => item.trim()).filter(Boolean).map((item) => {
1124
+ const [label, css] = item.includes("=") ? item.split("=") : [item, item];
1125
+ return { label: label.trim(), value: (css ?? label).trim() };
1126
+ });
1127
+ }
1128
+ function blobInfo(file) {
1129
+ let base64 = "";
1130
+ const ready = new Promise((resolve) => {
1131
+ const reader = new FileReader();
1132
+ reader.onload = () => {
1133
+ base64 = String(reader.result).replace(/^data:[^,]*,/, "");
1134
+ resolve();
1135
+ };
1136
+ reader.onerror = () => resolve();
1137
+ reader.readAsDataURL(file);
1138
+ });
1139
+ let uri = "";
1140
+ return {
1141
+ ready,
1142
+ info: {
1143
+ id: () => file.name.replace(/\.[^.]+$/, "") || "image",
1144
+ name: () => file.name.replace(/\.[^.]+$/, "") || "image",
1145
+ filename: () => file.name || "image",
1146
+ blob: () => file,
1147
+ base64: () => base64,
1148
+ blobUri: () => uri ||= URL.createObjectURL(file),
1149
+ uri: () => void 0
1150
+ }
1151
+ };
1152
+ }
1153
+ function mapOptions(config) {
1154
+ const unknown = Object.keys(config).filter((key) => !IGNORED.has(key));
1155
+ const plugins = [];
1156
+ const missingPlugins = [];
1157
+ for (const name of list(config.plugins)) {
1158
+ const target = RENAMED[name] ?? name;
1159
+ if (BUILT_IN.has(name)) continue;
1160
+ if ((0, import_core2.isPluginRegistered)(target)) plugins.push(target);
1161
+ else missingPlugins.push(name);
1162
+ }
1163
+ const options = { plugins };
1164
+ if (config.toolbar === false) options.toolbar = false;
1165
+ else if (Array.isArray(config.toolbar)) options.toolbar = config.toolbar.join(" | ");
1166
+ else if (typeof config.toolbar === "string") options.toolbar = config.toolbar;
1167
+ if (config.menubar !== void 0) options.menubar = config.menubar;
1168
+ if (typeof config.statusbar === "boolean") options.statusbar = config.statusbar;
1169
+ if (typeof config.placeholder === "string") options.placeholder = config.placeholder;
1170
+ if (config.readonly === true) options.editable = false;
1171
+ if (typeof config.language === "string") options.language = config.language.replace("_", "-");
1172
+ if (config.toolbar_mode === "sliding" || config.toolbar_mode === "wrap") {
1173
+ options.toolbarMode = config.toolbar_mode;
1174
+ } else if (config.toolbar_mode === "floating" || config.toolbar_mode === "scrolling") {
1175
+ options.toolbarMode = "sliding";
1176
+ }
1177
+ if (config.inline === true) options.mode = "inline";
1178
+ if (config.paste_as_text === true) options.pasteAsText = true;
1179
+ if (typeof config.paste_preprocess === "function") {
1180
+ const fn = config.paste_preprocess;
1181
+ options.pastePreprocess = (html, editor) => {
1182
+ const args = { content: html };
1183
+ fn(editor, args);
1184
+ return args.content;
1185
+ };
1186
+ }
1187
+ if (typeof config.invalid_elements === "string")
1188
+ options.invalidElements = config.invalid_elements;
1189
+ if (typeof config.valid_elements === "string") options.validElements = config.valid_elements;
1190
+ if (config.valid_styles) options.validStyles = config.valid_styles;
1191
+ const fonts = parseFormats(config.font_family_formats);
1192
+ if (fonts) options.fontFamilies = fonts;
1193
+ const sizes = parseFormats(config.font_size_formats);
1194
+ if (sizes) options.fontSizes = sizes.map((s) => s.value);
1195
+ const heights = parseFormats(config.line_height_formats);
1196
+ if (heights) options.lineHeights = heights.map((s) => s.value);
1197
+ if (Array.isArray(config.color_map)) {
1198
+ options.colors = config.color_map.filter((_, i) => i % 2 === 0).map((c) => c.startsWith("#") ? c : `#${c}`);
1199
+ }
1200
+ if (typeof config.images_upload_handler === "function") {
1201
+ const handler = config.images_upload_handler;
1202
+ const upload = async (file, progress) => {
1203
+ const { ready, info } = blobInfo(file);
1204
+ await ready;
1205
+ return handler(info, progress);
1206
+ };
1207
+ options.uploadImage = upload;
1208
+ }
1209
+ const pluginOptions = {};
1210
+ if (config.autosave_interval || config.autosave_retention || config.autosave_prefix) {
1211
+ const seconds = (value) => parseInt(String(value), 10);
1212
+ pluginOptions.autosave = {
1213
+ ...config.autosave_interval ? { delay: seconds(config.autosave_interval) * 1e3 } : {},
1214
+ ...config.autosave_retention ? { retention: seconds(config.autosave_retention) } : {},
1215
+ ...config.autosave_prefix ? { key: String(config.autosave_prefix) } : {}
1216
+ };
1217
+ }
1218
+ if (config.quickbars_selection_toolbar !== void 0 || config.quickbars_insert_toolbar !== void 0) {
1219
+ pluginOptions.quickbars = {
1220
+ ...config.quickbars_selection_toolbar !== void 0 ? { selection: config.quickbars_selection_toolbar } : {},
1221
+ ...config.quickbars_insert_toolbar !== void 0 ? { insert: config.quickbars_insert_toolbar } : {}
1222
+ };
1223
+ }
1224
+ if (typeof config.mentions_fetch === "function") {
1225
+ const fetch = config.mentions_fetch;
1226
+ pluginOptions.mentions = {
1227
+ fetch: (term) => new Promise((resolve) => fetch({ term }, resolve))
1228
+ };
1229
+ }
1230
+ if (config.tinycomments_author) {
1231
+ pluginOptions.comments = {
1232
+ author: {
1233
+ id: String(config.tinycomments_author),
1234
+ name: String(config.tinycomments_author_name ?? config.tinycomments_author)
1235
+ }
1236
+ };
1237
+ }
1238
+ if (Object.keys(pluginOptions).length) options.pluginOptions = pluginOptions;
1239
+ return { options, unknown, missingPlugins };
1240
+ }
1241
+
1242
+ // src/index.ts
1243
+ var warned = /* @__PURE__ */ new Set();
1244
+ function warnOnce(message) {
1245
+ if (warned.has(message)) return;
1246
+ warned.add(message);
1247
+ console.warn(`[nova] tinymce-compat: ${message}`);
1248
+ }
1249
+ var counter = 0;
1250
+ function applyContentStyle(core, css) {
1251
+ const scope = `nova-compat-${++counter}`;
1252
+ core.root.classList.add(scope);
1253
+ const style = document.createElement("style");
1254
+ style.setAttribute("data-nova-compat", scope);
1255
+ style.textContent = `.${scope} .nova-prosemirror { ${css.replace(/\b(html|body)\b/g, "&")} }`;
1256
+ core.root.prepend(style);
1257
+ }
1258
+ var px = (value) => typeof value === "number" ? `${value}px` : String(value);
1259
+ function createTinymce() {
1260
+ const all = [];
1261
+ const plugins = /* @__PURE__ */ new Map();
1262
+ let active = null;
1263
+ async function initOne(target, config) {
1264
+ const existing = all.find((e) => e.targetElm === target && !e.removed);
1265
+ if (existing) return existing;
1266
+ const { options, unknown, missingPlugins } = mapOptions(config);
1267
+ if (unknown.length) warnOnce(`options not supported yet: ${unknown.join(", ")}`);
1268
+ const custom = String(
1269
+ Array.isArray(config.plugins) ? config.plugins.join(" ") : config.plugins ?? ""
1270
+ ).split(/[\s,]+/).filter((name) => plugins.has(name));
1271
+ const missing = missingPlugins.filter((name) => !plugins.has(name));
1272
+ if (missing.length) warnOnce(`plugins not available: ${missing.join(", ")}`);
1273
+ const id = target.id || `mce_${++counter}`;
1274
+ if (!target.id) target.id = id;
1275
+ const isTextarea = target instanceof HTMLTextAreaElement;
1276
+ const initial = isTextarea ? target.value : target.innerHTML;
1277
+ const settings = { ...config, __initialContent: initial };
1278
+ let host;
1279
+ if (config.inline === true && !isTextarea) {
1280
+ target.replaceChildren();
1281
+ host = target;
1282
+ } else {
1283
+ host = document.createElement("div");
1284
+ host.className = "nova-compat";
1285
+ target.after(host);
1286
+ target.hidden = true;
1287
+ settings.__wrapper = host;
1288
+ }
1289
+ let compat;
1290
+ const core = (0, import_core3.createEditor)({
1291
+ ...options,
1292
+ element: host,
1293
+ content: initial,
1294
+ setup: (editor) => {
1295
+ compat = new CompatEditor(editor, target, id, settings);
1296
+ for (const name of custom) {
1297
+ try {
1298
+ plugins.get(name)(compat, "");
1299
+ } catch (error) {
1300
+ console.error(`[nova] tinymce-compat: plugin "${name}" failed`, error);
1301
+ }
1302
+ }
1303
+ config.setup?.(compat);
1304
+ }
1305
+ });
1306
+ if (config.height !== void 0) core.root.style.height = px(config.height);
1307
+ if (config.min_height !== void 0) core.root.style.minHeight = px(config.min_height);
1308
+ if (config.max_height !== void 0) core.root.style.maxHeight = px(config.max_height);
1309
+ if (config.width !== void 0) core.root.style.width = px(config.width);
1310
+ if (typeof config.content_style === "string") applyContentStyle(core, config.content_style);
1311
+ let changedSinceFocus = false;
1312
+ core.on("change", () => {
1313
+ compat.setDirty(true);
1314
+ changedSinceFocus = true;
1315
+ compat.fire("input");
1316
+ });
1317
+ core.on("selectionChange", () => {
1318
+ compat.fire("NodeChange", { element: compat.selection.getNode(), selectionChange: true });
1319
+ });
1320
+ core.on("focus", () => {
1321
+ active = compat;
1322
+ changedSinceFocus = false;
1323
+ compat.fire("focus");
1324
+ });
1325
+ core.on("blur", () => {
1326
+ if (changedSinceFocus) compat.fire("change", { level: { content: compat.getContent() } });
1327
+ changedSinceFocus = false;
1328
+ compat.fire("blur");
1329
+ });
1330
+ for (const name of [
1331
+ "keydown",
1332
+ "keyup",
1333
+ "keypress",
1334
+ "click",
1335
+ "dblclick",
1336
+ "mousedown",
1337
+ "mouseup",
1338
+ "paste",
1339
+ "copy",
1340
+ "cut",
1341
+ "drop"
1342
+ ]) {
1343
+ core.view.dom.addEventListener(name, (event) => compat.fireNative(name, event));
1344
+ }
1345
+ const form = isTextarea ? target.form : target.closest("form");
1346
+ form?.addEventListener("submit", () => compat.save());
1347
+ compat.on("remove", () => {
1348
+ const index = all.indexOf(compat);
1349
+ if (index >= 0) all.splice(index, 1);
1350
+ if (active === compat) active = all[0] ?? null;
1351
+ });
1352
+ all.push(compat);
1353
+ active ??= compat;
1354
+ await core.ready;
1355
+ if (compat.removed) return compat;
1356
+ compat.initialized = true;
1357
+ compat.fire("init");
1358
+ config.init_instance_callback?.(compat);
1359
+ return compat;
1360
+ }
1361
+ const api = {
1362
+ majorVersion: "7",
1363
+ minorVersion: "0.0",
1364
+ novaprose: true,
1365
+ get activeEditor() {
1366
+ return active;
1367
+ },
1368
+ get editors() {
1369
+ return [...all];
1370
+ },
1371
+ async init(config) {
1372
+ if (document.readyState === "loading") {
1373
+ await new Promise(
1374
+ (resolve) => document.addEventListener("DOMContentLoaded", resolve, { once: true })
1375
+ );
1376
+ }
1377
+ const targets = config.target ? [config.target] : config.selector ? [...document.querySelectorAll(config.selector)] : [];
1378
+ if (!targets.length) warnOnce(`no elements match "${config.selector ?? ""}"`);
1379
+ const editors = [];
1380
+ for (const target of targets) editors.push(await initOne(target, config));
1381
+ return editors;
1382
+ },
1383
+ get: ((id) => {
1384
+ if (id === void 0) return [...all];
1385
+ if (typeof id === "number") return all[id] ?? null;
1386
+ return all.find((e) => e.id === id) ?? null;
1387
+ }),
1388
+ remove(selector) {
1389
+ const targets = selector === void 0 ? [...all] : typeof selector === "string" ? all.filter(
1390
+ (e) => e.id === selector.replace(/^#/, "") || e.targetElm.matches(selector)
1391
+ ) : [selector];
1392
+ targets.forEach((editor) => editor.remove());
1393
+ },
1394
+ triggerSave() {
1395
+ all.forEach((editor) => editor.save());
1396
+ },
1397
+ execCommand(command, ui, value) {
1398
+ return active?.execCommand(command, ui, value) ?? false;
1399
+ },
1400
+ PluginManager: {
1401
+ add: (name, plugin) => {
1402
+ plugins.set(name, plugin);
1403
+ },
1404
+ get: (name) => plugins.get(name),
1405
+ requireLangPack: () => {
1406
+ },
1407
+ urls: {}
1408
+ },
1409
+ IconManager: {
1410
+ add: (_name, pack) => {
1411
+ for (const [icon, svg] of Object.entries(pack.icons ?? {})) {
1412
+ CompatEditor.registerIcon(icon, svg);
1413
+ }
1414
+ }
1415
+ },
1416
+ util: { I18n: { translate: (text) => text } }
1417
+ };
1418
+ return api;
1419
+ }
1420
+ var tinymce = createTinymce();
1421
+ // Annotate the CommonJS export names for ESM import in node:
1422
+ 0 && (module.exports = {
1423
+ CompatEditor,
1424
+ createTinymce,
1425
+ mapOptions,
1426
+ tinymce
1427
+ });
1428
+ //# sourceMappingURL=index.cjs.map