@novaprose/tinymce-compat 0.4.0 → 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.js CHANGED
@@ -2,7 +2,308 @@
2
2
  import { createEditor } from "@novaprose/core";
3
3
 
4
4
  // src/editor.ts
5
- import { HTMLSerializer, icons, parserFor } from "@novaprose/core";
5
+ import {
6
+ getStyle,
7
+ HTMLSerializer,
8
+ icons,
9
+ parserFor,
10
+ setStyle
11
+ } from "@novaprose/core";
12
+
13
+ // src/dialog.ts
14
+ var uid = 0;
15
+ var nextId = () => `nova-compat-field-${++uid}`;
16
+ function el(tag, className, text) {
17
+ const node = document.createElement(tag);
18
+ if (className) node.className = className;
19
+ if (text !== void 0) node.textContent = text;
20
+ return node;
21
+ }
22
+ function safeHtml(html) {
23
+ const template = document.createElement("template");
24
+ template.innerHTML = html;
25
+ template.content.querySelectorAll("script, style, iframe, object, embed, link, meta, base, form").forEach((node) => node.remove());
26
+ template.content.querySelectorAll("*").forEach((node) => {
27
+ for (const attr of [...node.attributes]) {
28
+ const value = attr.value.trim().toLowerCase();
29
+ if (attr.name.startsWith("on") || /^(javascript|vbscript|data):/.test(value)) {
30
+ node.removeAttribute(attr.name);
31
+ }
32
+ }
33
+ });
34
+ return template.content;
35
+ }
36
+ function openSpecDialog(editor, spec, reopen) {
37
+ const controls = /* @__PURE__ */ new Map();
38
+ const tabs = /* @__PURE__ */ new Map();
39
+ let currentTab = "";
40
+ let closedByApi = false;
41
+ let handle = null;
42
+ const notifyChange = (name) => spec.onChange?.(api, { name });
43
+ function field(item, input) {
44
+ const id = nextId();
45
+ input.id = id;
46
+ const wrap = el("div", "nova-field");
47
+ if (item.label) {
48
+ const label = el("label", "nova-label", item.label);
49
+ label.htmlFor = id;
50
+ wrap.append(label);
51
+ }
52
+ wrap.append(input);
53
+ return wrap;
54
+ }
55
+ function render(item) {
56
+ const name = item.name ?? "";
57
+ const enabled = item.enabled !== false && item.disabled !== true;
58
+ switch (item.type) {
59
+ case "input":
60
+ case "urlinput":
61
+ case "colorinput": {
62
+ const input = el("input", "nova-input");
63
+ input.type = item.type === "colorinput" ? "color" : item.type === "urlinput" ? "url" : "text";
64
+ if (item.inputMode) input.inputMode = item.inputMode;
65
+ if (item.placeholder) input.placeholder = item.placeholder;
66
+ input.disabled = !enabled;
67
+ input.addEventListener("input", () => notifyChange(name));
68
+ if (name) {
69
+ controls.set(name, {
70
+ // urlinput хранит { value }, остальные — строку.
71
+ get: () => item.type === "urlinput" ? { value: input.value } : input.value,
72
+ set: (value) => {
73
+ input.value = String(
74
+ item.type === "urlinput" && value && typeof value === "object" ? value.value ?? "" : value ?? ""
75
+ );
76
+ },
77
+ focus: () => input.focus(),
78
+ setEnabled: (on) => input.disabled = !on
79
+ });
80
+ }
81
+ return field(item, input);
82
+ }
83
+ case "textarea": {
84
+ const input = el("textarea", "nova-input");
85
+ input.rows = item.maximized ? 10 : 4;
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
+ get: () => input.value,
92
+ set: (value) => input.value = String(value ?? ""),
93
+ focus: () => input.focus(),
94
+ setEnabled: (on) => input.disabled = !on
95
+ });
96
+ }
97
+ return field(item, input);
98
+ }
99
+ case "checkbox": {
100
+ const input = el("input", "nova-checkbox");
101
+ input.type = "checkbox";
102
+ input.id = nextId();
103
+ input.disabled = !enabled;
104
+ input.addEventListener("change", () => notifyChange(name));
105
+ const label = el("label", void 0, item.label ?? "");
106
+ label.htmlFor = input.id;
107
+ if (name) {
108
+ controls.set(name, {
109
+ get: () => input.checked,
110
+ set: (value) => input.checked = Boolean(value),
111
+ focus: () => input.focus(),
112
+ setEnabled: (on) => input.disabled = !on
113
+ });
114
+ }
115
+ const wrap = el("div", "nova-field nova-field-inline");
116
+ wrap.append(input, label);
117
+ return wrap;
118
+ }
119
+ case "selectbox":
120
+ case "listbox": {
121
+ const select = el("select", "nova-input nova-select");
122
+ for (const option of item.items ?? []) {
123
+ const node = el("option", void 0, option.text);
124
+ node.value = option.value;
125
+ select.append(node);
126
+ }
127
+ select.disabled = !enabled;
128
+ select.addEventListener("change", () => notifyChange(name));
129
+ if (name) {
130
+ controls.set(name, {
131
+ get: () => select.value,
132
+ set: (value) => select.value = String(value ?? ""),
133
+ focus: () => select.focus(),
134
+ setEnabled: (on) => select.disabled = !on
135
+ });
136
+ }
137
+ return field(item, select);
138
+ }
139
+ case "button": {
140
+ const button = el(
141
+ "button",
142
+ item.primary || item.buttonType === "primary" ? "nova-button nova-button-primary" : "nova-button",
143
+ item.text ?? ""
144
+ );
145
+ button.type = "button";
146
+ button.disabled = !enabled;
147
+ button.addEventListener("click", () => spec.onAction?.(api, { name }));
148
+ if (name) {
149
+ controls.set(name, {
150
+ get: () => void 0,
151
+ set: () => {
152
+ },
153
+ focus: () => button.focus(),
154
+ setEnabled: (on) => button.disabled = !on
155
+ });
156
+ }
157
+ return button;
158
+ }
159
+ case "htmlpanel": {
160
+ const panel = el("div", "nova-compat-html");
161
+ panel.append(safeHtml(item.html ?? ""));
162
+ return panel;
163
+ }
164
+ case "alertbanner": {
165
+ const banner = el("p", `nova-compat-alert is-${item.level ?? "info"}`, item.text ?? "");
166
+ banner.setAttribute("role", item.level === "error" ? "alert" : "status");
167
+ return banner;
168
+ }
169
+ case "label": {
170
+ const group = el("div", "nova-compat-group");
171
+ group.append(el("p", "nova-label", item.label ?? ""));
172
+ for (const child of item.items ?? []) {
173
+ const node = render(child);
174
+ if (node) group.append(node);
175
+ }
176
+ return group;
177
+ }
178
+ case "grid":
179
+ case "bar": {
180
+ const grid = el("div", "nova-compat-grid");
181
+ const columns = item.type === "bar" ? item.items?.length ?? 1 : item.columns === "auto" ? 2 : item.columns ?? 2;
182
+ grid.style.gridTemplateColumns = `repeat(${Number(columns) || 2}, minmax(0, 1fr))`;
183
+ for (const child of item.items ?? []) {
184
+ const node = render(child);
185
+ if (node) grid.append(node);
186
+ }
187
+ return grid;
188
+ }
189
+ default:
190
+ console.warn(`[nova] tinymce-compat: dialog component "${item.type}" is not supported yet`);
191
+ return null;
192
+ }
193
+ }
194
+ const body = el("div", "nova-compat-dialog nova-form");
195
+ if (spec.body.type === "tabpanel") {
196
+ const tabList = el("div", "nova-compat-tabs");
197
+ tabList.setAttribute("role", "tablist");
198
+ body.append(tabList);
199
+ spec.body.tabs.forEach((tab, index) => {
200
+ const name = tab.name ?? tab.title;
201
+ const button = el("button", "nova-compat-tab", tab.title);
202
+ button.type = "button";
203
+ button.setAttribute("role", "tab");
204
+ const panel = el("div", "nova-compat-tabpanel");
205
+ panel.setAttribute("role", "tabpanel");
206
+ for (const item of tab.items) {
207
+ const node = render(item);
208
+ if (node) panel.append(node);
209
+ }
210
+ button.addEventListener("click", () => api.showTab(name));
211
+ tabs.set(name, { button, panel });
212
+ tabList.append(button);
213
+ body.append(panel);
214
+ if (index === 0) currentTab = name;
215
+ });
216
+ } else {
217
+ for (const item of spec.body.items) {
218
+ const node = render(item);
219
+ if (node) body.append(node);
220
+ }
221
+ }
222
+ const buttons = spec.buttons ?? [];
223
+ const submit = buttons.find((b) => b.type === "submit");
224
+ const custom = buttons.filter((b) => b.type === "custom");
225
+ if (custom.length) {
226
+ const row = el("div", "nova-compat-actions");
227
+ for (const b of custom) {
228
+ const button = el(
229
+ "button",
230
+ b.primary ? "nova-button nova-button-primary" : "nova-button",
231
+ b.text
232
+ );
233
+ button.type = "button";
234
+ button.disabled = b.enabled === false;
235
+ button.addEventListener("click", () => spec.onAction?.(api, { name: b.name ?? b.text }));
236
+ if (b.name) {
237
+ controls.set(b.name, {
238
+ get: () => void 0,
239
+ set: () => {
240
+ },
241
+ focus: () => button.focus(),
242
+ setEnabled: (on) => button.disabled = !on
243
+ });
244
+ }
245
+ row.append(button);
246
+ }
247
+ body.append(row);
248
+ }
249
+ const api = {
250
+ getData: () => {
251
+ const data = {};
252
+ controls.forEach((control, name) => {
253
+ const value = control.get();
254
+ if (value !== void 0) data[name] = value;
255
+ });
256
+ return data;
257
+ },
258
+ setData: (data) => {
259
+ for (const [name, value] of Object.entries(data)) controls.get(name)?.set(value);
260
+ },
261
+ close: () => {
262
+ closedByApi = true;
263
+ handle?.close();
264
+ },
265
+ block: () => handle?.setBusy(true),
266
+ unblock: () => handle?.setBusy(false),
267
+ focus: (name) => controls.get(name)?.focus(),
268
+ disable: (name) => controls.get(name)?.setEnabled(false),
269
+ enable: (name) => controls.get(name)?.setEnabled(true),
270
+ showTab: (name) => {
271
+ if (!tabs.has(name)) return;
272
+ const old = currentTab;
273
+ currentTab = name;
274
+ tabs.forEach(({ button, panel }, key) => {
275
+ const on = key === name;
276
+ button.setAttribute("aria-selected", String(on));
277
+ button.tabIndex = on ? 0 : -1;
278
+ panel.hidden = !on;
279
+ });
280
+ if (old && old !== name) spec.onTabChange?.(api, { newTabName: name, oldTabName: old });
281
+ },
282
+ redial: (next) => {
283
+ api.close();
284
+ Object.assign(api, reopen(next));
285
+ }
286
+ };
287
+ if (spec.initialData) api.setData(spec.initialData);
288
+ if (currentTab) api.showTab(currentTab);
289
+ handle = editor.ui.openDialog({
290
+ title: spec.title,
291
+ body,
292
+ ...submit ? { submitLabel: submit.text } : {},
293
+ ...spec.size === "large" ? { size: "large" } : {},
294
+ onSubmit: () => {
295
+ spec.onSubmit?.(api);
296
+ return closedByApi;
297
+ },
298
+ onClose: () => {
299
+ if (!closedByApi) spec.onCancel?.(api);
300
+ spec.onClose?.();
301
+ }
302
+ });
303
+ return api;
304
+ }
305
+
306
+ // src/editor.ts
6
307
  import { Slice } from "prosemirror-model";
7
308
  import { AllSelection, TextSelection } from "prosemirror-state";
8
309
  var serializer = new HTMLSerializer();
@@ -97,6 +398,55 @@ var ICON_NAMES = {
97
398
  "highlight-bg-color": "highlight",
98
399
  "line-height": "lineHeight"
99
400
  };
401
+ var FORMAT_COMMANDS = {
402
+ bold: "bold",
403
+ italic: "italic",
404
+ underline: "underline",
405
+ strikethrough: "strike",
406
+ superscript: "superscript",
407
+ subscript: "subscript",
408
+ code: "code",
409
+ p: "paragraph",
410
+ h1: "h1",
411
+ h2: "h2",
412
+ h3: "h3",
413
+ h4: "h4",
414
+ h5: "h5",
415
+ h6: "h6",
416
+ blockquote: "blockquote",
417
+ pre: "codeBlock",
418
+ alignleft: "alignLeft",
419
+ aligncenter: "alignCenter",
420
+ alignright: "alignRight",
421
+ alignjustify: "alignJustify"
422
+ };
423
+ var TAG_FORMATS = /* @__PURE__ */ new Set(["p", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "pre"]);
424
+ var BLOCK_FORMATS = /* @__PURE__ */ new Set([
425
+ "p",
426
+ "h1",
427
+ "h2",
428
+ "h3",
429
+ "h4",
430
+ "h5",
431
+ "h6",
432
+ "blockquote",
433
+ "pre",
434
+ "alignleft",
435
+ "aligncenter",
436
+ "alignright",
437
+ "alignjustify"
438
+ ]);
439
+ var STYLE_FORMATS = {
440
+ forecolor: "color",
441
+ hilitecolor: "background",
442
+ fontname: "font_family",
443
+ fontsize: "font_size"
444
+ };
445
+ function warnDom(method) {
446
+ console.warn(
447
+ `[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.`
448
+ );
449
+ }
100
450
  var customIcons = /* @__PURE__ */ new Map();
101
451
  function resolveIcon(name) {
102
452
  if (typeof name !== "string" || !name) return void 0;
@@ -177,7 +527,7 @@ var CompatEditor = class {
177
527
  const container = document.createElement("div");
178
528
  container.append(template.content);
179
529
  const parser = parserFor(this.core.schema);
180
- const hasBlocks = [...container.children].some((el) => BLOCK_TAGS.has(el.tagName));
530
+ const hasBlocks = [...container.children].some((el2) => BLOCK_TAGS.has(el2.tagName));
181
531
  const slice = hasBlocks ? new Slice(parser.parse(container).content, 0, 0) : parser.parseSlice(container);
182
532
  const { state, dispatch } = this.core.view;
183
533
  dispatch(state.tr.replaceSelection(slice).scrollIntoView());
@@ -433,13 +783,7 @@ var CompatEditor = class {
433
783
  onClose: () => callback?.(confirmed)
434
784
  });
435
785
  },
436
- open: () => {
437
- console.warn(
438
- "[nova] tinymce-compat: windowManager.open is not supported yet \u2014 use editor.ui.openDialog"
439
- );
440
- return { close: () => {
441
- } };
442
- }
786
+ open: (spec) => openSpecDialog(this.core, spec, (next) => this.windowManager.open(next))
443
787
  };
444
788
  /** editor.ui.registry — кнопки и пункты меню в формате TinyMCE поверх реестра NovaProse. */
445
789
  ui = {
@@ -476,8 +820,23 @@ var CompatEditor = class {
476
820
  onAction: () => spec.onAction?.({})
477
821
  });
478
822
  },
479
- addContextToolbar: () => {
480
- console.warn("[nova] tinymce-compat: addContextToolbar is not supported yet");
823
+ /**
824
+ * Контекстная панель: predicate(node) получает элемент под курсором, items — кнопки тулбара.
825
+ * position: 'node' (над элементом) или 'selection'/'line' (у выделения).
826
+ */
827
+ addContextToolbar: (name, spec) => {
828
+ this.core.ui.registry.addContextToolbar(name, {
829
+ label: spec.label ?? name,
830
+ items: spec.items,
831
+ position: spec.position === "node" ? "node" : "selection",
832
+ predicate: () => {
833
+ const node = this.selection.getNode();
834
+ return !!node && this.getBody().contains(node) && spec.predicate(node);
835
+ }
836
+ });
837
+ },
838
+ addContextForm: () => {
839
+ console.warn("[nova] tinymce-compat: addContextForm is not supported yet");
481
840
  },
482
841
  getAll: () => ({})
483
842
  }
@@ -503,6 +862,131 @@ var CompatEditor = class {
503
862
  else this.once("init", run);
504
863
  }
505
864
  }
865
+ /**
866
+ * editor.dom — то, что имеет смысл поверх модели документа: поиск и чтение. Менять DOM текста
867
+ * напрямую нельзя (редактор перерисует его из модели) — для правок есть setContent/insertContent/
868
+ * formatter; такие вызовы пишут предупреждение.
869
+ */
870
+ dom = {
871
+ select: (selector, scope) => [
872
+ ...(scope ?? this.getBody()).querySelectorAll(selector)
873
+ ],
874
+ get: (id) => typeof id === "string" ? this.getBody().querySelector(`#${CSS.escape(id)}`) : id,
875
+ getParent: (node, selector) => {
876
+ let current = node instanceof Element ? node : node?.parentElement ?? null;
877
+ while (current && current !== this.getBody()) {
878
+ if (typeof selector === "string" ? current.matches(selector) : selector(current))
879
+ return current;
880
+ current = current.parentElement;
881
+ }
882
+ return null;
883
+ },
884
+ getParents: (node, selector) => {
885
+ const result = [];
886
+ let current = node instanceof Element ? node : node?.parentElement ?? null;
887
+ while (current && current !== this.getBody()) {
888
+ if (!selector || current.matches(selector)) result.push(current);
889
+ current = current.parentElement;
890
+ }
891
+ return result;
892
+ },
893
+ is: (node, selector) => !!node?.matches(selector),
894
+ getAttrib: (node, name, fallback = "") => node?.getAttribute(name) ?? fallback,
895
+ hasClass: (node, name) => !!node?.classList.contains(name),
896
+ getStyle: (node, name) => node instanceof HTMLElement ? node.style.getPropertyValue(name) : "",
897
+ getRoot: () => this.getBody(),
898
+ encode: (text) => text.replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`),
899
+ decode: (html) => {
900
+ const textarea = document.createElement("textarea");
901
+ textarea.innerHTML = html;
902
+ return textarea.value;
903
+ },
904
+ /** Новый (не вставленный) элемент: атрибуты — через setAttribute, содержимое — текстом. */
905
+ create: (tag, attrs = {}, text) => {
906
+ const node = document.createElement(tag);
907
+ for (const [name, value] of Object.entries(attrs)) {
908
+ if (!name.startsWith("on")) node.setAttribute(name, value);
909
+ }
910
+ if (text !== void 0) node.textContent = text;
911
+ return node;
912
+ },
913
+ uniqueId: (prefix = "mce_") => `${prefix}${Math.random().toString(36).slice(2, 10)}`,
914
+ setAttrib: () => warnDom("setAttrib"),
915
+ addClass: () => warnDom("addClass"),
916
+ removeClass: () => warnDom("removeClass"),
917
+ setStyle: () => warnDom("setStyle"),
918
+ remove: () => warnDom("remove")
919
+ };
920
+ /**
921
+ * editor.formatter — встроенные форматы TinyMCE: apply/remove/toggle/match.
922
+ * Свои форматы (register) пока не поддержаны.
923
+ */
924
+ formatter = {
925
+ apply: (name, vars = {}) => this.applyFormat(name, vars, "apply"),
926
+ remove: (name) => this.applyFormat(name, {}, "remove"),
927
+ toggle: (name, vars = {}) => this.applyFormat(name, vars, this.formatter.match(name) ? "remove" : "apply"),
928
+ match: (name) => {
929
+ const key = name.toLowerCase();
930
+ if (TAG_FORMATS.has(key)) return this.blockMatches(key);
931
+ const command = FORMAT_COMMANDS[key];
932
+ if (command) return this.core.isActive(command);
933
+ const style = STYLE_FORMATS[key];
934
+ if (!style) return false;
935
+ const { state } = this.core.view;
936
+ const { from, to, empty } = state.selection;
937
+ const type = state.schema.marks[style];
938
+ return empty || !type ? getStyle(state, style) !== null : state.doc.rangeHasMark(from, to, type);
939
+ },
940
+ canApply: (name) => name.toLowerCase() in FORMAT_COMMANDS || name.toLowerCase() in STYLE_FORMATS,
941
+ register: (name) => {
942
+ console.warn(`[nova] tinymce-compat: formatter.register("${name}") is not supported yet`);
943
+ }
944
+ };
945
+ blockMatches(key) {
946
+ const { $from } = this.core.view.state.selection;
947
+ for (let depth = $from.depth; depth > 0; depth -= 1) {
948
+ const node = $from.node(depth);
949
+ const name = node.type.name;
950
+ if (key === "blockquote" && name === "blockquote") return true;
951
+ if (depth !== $from.depth) continue;
952
+ if (key === "p") return name === "paragraph";
953
+ if (key === "pre") return name === "code_block";
954
+ if (/^h[1-6]$/.test(key)) return name === "heading" && node.attrs.level === Number(key[1]);
955
+ }
956
+ let first = null;
957
+ this.core.view.state.doc.descendants((node) => {
958
+ if (first || !node.isTextblock) return !first;
959
+ first = { name: node.type.name, level: node.attrs.level };
960
+ return false;
961
+ });
962
+ if (!$from.depth && first) {
963
+ const block = first;
964
+ if (key === "p") return block.name === "paragraph";
965
+ if (key === "pre") return block.name === "code_block";
966
+ if (/^h[1-6]$/.test(key)) return block.name === "heading" && block.level === Number(key[1]);
967
+ }
968
+ return false;
969
+ }
970
+ applyFormat(name, vars, action) {
971
+ const key = name.toLowerCase();
972
+ const command = FORMAT_COMMANDS[key];
973
+ if (command) {
974
+ const active = this.formatter.match(key);
975
+ if (BLOCK_FORMATS.has(key)) {
976
+ if (action === "apply") this.core.exec(command);
977
+ else if (active) this.core.exec("paragraph");
978
+ } else if (action === "apply" !== active) {
979
+ this.core.exec(command);
980
+ }
981
+ return;
982
+ }
983
+ const style = STYLE_FORMATS[key];
984
+ if (style) {
985
+ this.core.exec(setStyle(style, action === "apply" ? vars.value ?? null : null));
986
+ return;
987
+ }
988
+ console.warn(`[nova] tinymce-compat: format "${name}" is not supported yet`);
989
+ }
506
990
  /** Убрать редактор и вернуть исходный элемент (как editor.remove()). */
507
991
  remove() {
508
992
  if (this.removed) return;