@novaprose/core 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +106 -2
  3. package/dist/advlist-FRIJ6LO7.js +107 -0
  4. package/dist/advlist-FRIJ6LO7.js.map +1 -0
  5. package/dist/autolink-ZVHNOOS7.js +89 -0
  6. package/dist/autolink-ZVHNOOS7.js.map +1 -0
  7. package/dist/autoresize-WT4ONZKK.js +26 -0
  8. package/dist/autoresize-WT4ONZKK.js.map +1 -0
  9. package/dist/autosave-2KI5WGV5.js +99 -0
  10. package/dist/autosave-2KI5WGV5.js.map +1 -0
  11. package/dist/charmap-3LM5LZCC.js +197 -0
  12. package/dist/charmap-3LM5LZCC.js.map +1 -0
  13. package/dist/chunk-6RJENZXT.js +104 -0
  14. package/dist/chunk-6RJENZXT.js.map +1 -0
  15. package/dist/chunk-AGBQEZ2U.js +1068 -0
  16. package/dist/chunk-AGBQEZ2U.js.map +1 -0
  17. package/dist/chunk-F6TSOU5U.js +80 -0
  18. package/dist/chunk-F6TSOU5U.js.map +1 -0
  19. package/dist/chunk-GHEFKKRC.js +268 -0
  20. package/dist/chunk-GHEFKKRC.js.map +1 -0
  21. package/dist/chunk-HZRIBOPW.js +52 -0
  22. package/dist/chunk-HZRIBOPW.js.map +1 -0
  23. package/dist/chunk-YZPJQB3I.js +490 -0
  24. package/dist/chunk-YZPJQB3I.js.map +1 -0
  25. package/dist/directionality-VSDWPWHX.js +70 -0
  26. package/dist/directionality-VSDWPWHX.js.map +1 -0
  27. package/dist/emoticons-YVGVA76P.js +216 -0
  28. package/dist/emoticons-YVGVA76P.js.map +1 -0
  29. package/dist/index.cjs +8590 -0
  30. package/dist/index.cjs.map +1 -0
  31. package/dist/index.d.cts +1357 -0
  32. package/dist/index.d.ts +1357 -0
  33. package/dist/index.js +5420 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/insertdatetime-QYWZUYO4.js +64 -0
  36. package/dist/insertdatetime-QYWZUYO4.js.map +1 -0
  37. package/dist/nonbreaking-SIACL5V6.js +46 -0
  38. package/dist/nonbreaking-SIACL5V6.js.map +1 -0
  39. package/dist/quickbars-WW3TGVCS.js +94 -0
  40. package/dist/quickbars-WW3TGVCS.js.map +1 -0
  41. package/dist/visualblocks-WB6NAEGB.js +43 -0
  42. package/dist/visualblocks-WB6NAEGB.js.map +1 -0
  43. package/package.json +67 -3
  44. package/src/style.css +1731 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NovaProse authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,107 @@
1
- # Temporary Holding Version
1
+ # @novaprose/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **NovaProse** is an embeddable rich text (WYSIWYG) editor built on [ProseMirror](https://prosemirror.net).
4
+ It is an open-source (MIT) alternative to TinyMCE: toolbar, plugin and option names follow the
5
+ conventions you already know, while the output is clean, deterministic HTML.
6
+
7
+ > **Status: 0.x preview.** The API may change between minor versions until 1.0.
8
+
9
+ - **Secure by default.** Every link and image URL is checked on input _and_ on output, dangerous
10
+ markup is dropped, and the UI never injects user content with `innerHTML`.
11
+ - **Deterministic HTML.** `getHTML()` produces the same string in every browser, so diffs and
12
+ snapshot tests stay stable.
13
+ - **Accessible.** ARIA roles, full keyboard support (Alt+F10 toolbar, Alt+F9 menu bar, Esc),
14
+ visible focus, screen-reader labels.
15
+ - **Complete out of the box.** Tables, images with upload and resize, links, colors, fonts, line
16
+ height, search and replace, source code view, fullscreen, menu bar, slash commands, Markdown
17
+ shortcuts, paste sanitizing (anything outside the schema is dropped), English and Russian UI,
18
+ light and dark theme. Dedicated Word and Excel paste cleanup is on the roadmap.
19
+ - **Small.** About 120 KB gzip including ProseMirror and tables. Optional plugins load lazily.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ npm install @novaprose/core
25
+ ```
26
+
27
+ ```ts
28
+ import { createEditor } from '@novaprose/core';
29
+ import '@novaprose/core/style.css';
30
+
31
+ const editor = createEditor({
32
+ element: document.querySelector('#editor')!,
33
+ content: '<p>Hello, world</p>',
34
+ placeholder: 'Start typing…',
35
+ // Familiar toolbar syntax; "|" separates groups. Items that don't fit move into "⋯".
36
+ toolbar:
37
+ 'undo redo | blocks | bold italic underline | forecolor backcolor | link image table | bullist numlist',
38
+ // Upload pasted, dropped and picked images to your server.
39
+ uploadImage: async (file) => {
40
+ const body = new FormData();
41
+ body.append('file', file);
42
+ const response = await fetch('/upload', { method: 'POST', body });
43
+ return (await response.json()).url;
44
+ },
45
+ onChange: (e) => console.log(e.getHTML()),
46
+ });
47
+
48
+ editor.exec('bold');
49
+ editor.getHTML();
50
+ editor.destroy();
51
+ ```
52
+
53
+ Using a framework? See [`@novaprose/react`](https://www.npmjs.com/package/@novaprose/react),
54
+ [`@novaprose/vue`](https://www.npmjs.com/package/@novaprose/vue),
55
+ [`@novaprose/angular`](https://www.npmjs.com/package/@novaprose/angular) or the framework-agnostic
56
+ [`@novaprose/web-component`](https://www.npmjs.com/package/@novaprose/web-component) (also for
57
+ Svelte, Astro and server-rendered pages, with a CDN build).
58
+
59
+ ## Options
60
+
61
+ | Option | Description |
62
+ | ---------------------------------------------------- | -------------------------------------------------------------------------------- |
63
+ | `element` | container to mount into (required) |
64
+ | `content` | initial HTML string or document JSON |
65
+ | `toolbar` | string (`'bold italic \| link'`), array of groups, or `false` |
66
+ | `toolbarMode` | `'sliding'` (default) or `'wrap'` |
67
+ | `mode` | `'classic'`, `'inline'` (toolbar on focus) or `'distraction-free'` (quick bars) |
68
+ | `menubar`, `menu` | File · Edit · View · Insert · Format · Table · Help menus, customizable |
69
+ | `statusbar` | word count and path; `false` to hide |
70
+ | `placeholder`, `editable`, `language` | placeholder text, read-only mode, UI language (`en`, `ru` or your own) |
71
+ | `uploadImage` | `(file, progress) => Promise<url>` |
72
+ | `fontFamilies`, `fontSizes`, `lineHeights`, `colors` | lists for the corresponding pickers |
73
+ | `plugins`, `pluginOptions` | plugin objects or names of built-in lazy plugins (`insertdatetime`, `quickbars`) |
74
+ | `validElements`, `invalidElements`, `validStyles` | restrict content, like TinyMCE `valid_elements` / `invalid_elements` |
75
+ | `pastePreprocess`, `pastePostprocess`, `pasteAsText` | paste hooks and plain-text mode |
76
+ | `setup`, `onChange` | access the instance before first render; change callback |
77
+ | `prosemirrorPlugins` | raw ProseMirror plugins for advanced use |
78
+
79
+ ## API
80
+
81
+ ```ts
82
+ editor.getHTML();
83
+ editor.getJSON();
84
+ editor.getText();
85
+ editor.isEmpty();
86
+ editor.setContent(html, { addToHistory: false });
87
+ editor.exec('bold');
88
+ editor.can('undo');
89
+ editor.isActive('h2');
90
+ editor.setEditable(false);
91
+ editor.focus();
92
+ editor.on('change' | 'selectionChange' | 'focus' | 'blur' | 'editableChange' | 'destroy', handler);
93
+ editor.ui.registry.addButton('signature', { text: 'Sign', onAction: (e) => e.exec('bold') });
94
+ editor.destroy();
95
+ ```
96
+
97
+ Command names (`bold`, `italic`, `h1`…`h6`, `bulletList`, `alignCenter`, `undo`…) are part of the
98
+ public API and stay stable across minor versions.
99
+
100
+ ## Server-side rendering
101
+
102
+ Importing the package never touches `window` or `document`, so it is safe in SSR bundles. Create
103
+ the editor only in the browser.
104
+
105
+ ## License
106
+
107
+ MIT
@@ -0,0 +1,107 @@
1
+ import {
2
+ BULLET_STYLES,
3
+ ORDERED_STYLES
4
+ } from "./chunk-YZPJQB3I.js";
5
+ import {
6
+ nodesOf
7
+ } from "./chunk-GHEFKKRC.js";
8
+ import {
9
+ pickLabels
10
+ } from "./chunk-6RJENZXT.js";
11
+ import "./chunk-HZRIBOPW.js";
12
+ import {
13
+ definePlugin
14
+ } from "./chunk-F6TSOU5U.js";
15
+
16
+ // src/plugins/advlist.ts
17
+ var LABELS = {
18
+ en: {
19
+ disc: "Default",
20
+ circle: "Circle",
21
+ square: "Square",
22
+ decimal: "Default (1, 2, 3)",
23
+ "lower-alpha": "Lower alpha (a, b, c)",
24
+ "upper-alpha": "Upper alpha (A, B, C)",
25
+ "lower-roman": "Lower roman (i, ii, iii)",
26
+ "upper-roman": "Upper roman (I, II, III)",
27
+ "lower-greek": "Lower greek (\u03B1, \u03B2, \u03B3)"
28
+ },
29
+ ru: {
30
+ disc: "\u041F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E",
31
+ circle: "\u041A\u0440\u0443\u0436\u043E\u043A",
32
+ square: "\u041A\u0432\u0430\u0434\u0440\u0430\u0442",
33
+ decimal: "\u041F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E (1, 2, 3)",
34
+ "lower-alpha": "\u0421\u0442\u0440\u043E\u0447\u043D\u044B\u0435 \u0431\u0443\u043A\u0432\u044B (a, b, c)",
35
+ "upper-alpha": "\u041F\u0440\u043E\u043F\u0438\u0441\u043D\u044B\u0435 \u0431\u0443\u043A\u0432\u044B (A, B, C)",
36
+ "lower-roman": "\u0420\u0438\u043C\u0441\u043A\u0438\u0435 \u0441\u0442\u0440\u043E\u0447\u043D\u044B\u0435 (i, ii, iii)",
37
+ "upper-roman": "\u0420\u0438\u043C\u0441\u043A\u0438\u0435 \u043F\u0440\u043E\u043F\u0438\u0441\u043D\u044B\u0435 (I, II, III)",
38
+ "lower-greek": "\u0413\u0440\u0435\u0447\u0435\u0441\u043A\u0438\u0435 (\u03B1, \u03B2, \u03B3)"
39
+ }
40
+ };
41
+ function findList(state, type) {
42
+ const { $from } = state.selection;
43
+ for (let depth = $from.depth; depth > 0; depth--) {
44
+ const node = $from.node(depth);
45
+ if (node.type === type) return { pos: $from.before(depth), attrs: node.attrs };
46
+ }
47
+ return null;
48
+ }
49
+ function applyStyle(editor, kind, style, fallback) {
50
+ const type = () => nodesOf(editor.view.state)[kind];
51
+ if (!findList(editor.view.state, type()))
52
+ editor.exec(kind === "bullet_list" ? "bulletList" : "orderedList");
53
+ const list = findList(editor.view.state, type());
54
+ if (!list) return;
55
+ const { state, dispatch } = editor.view;
56
+ dispatch(
57
+ state.tr.setNodeMarkup(list.pos, void 0, {
58
+ ...list.attrs,
59
+ listStyle: style === fallback ? null : style
60
+ })
61
+ );
62
+ editor.focus();
63
+ }
64
+ var advlist_default = definePlugin({
65
+ name: "advlist",
66
+ setup(editor) {
67
+ const labels = pickLabels(editor, LABELS);
68
+ const options = editor.options.pluginOptions?.advlist ?? {};
69
+ const lists = [
70
+ {
71
+ control: "bullist",
72
+ kind: "bullet_list",
73
+ styles: options.bullets ?? [...BULLET_STYLES],
74
+ fallback: "disc"
75
+ },
76
+ {
77
+ control: "numlist",
78
+ kind: "ordered_list",
79
+ styles: options.numbers ?? [...ORDERED_STYLES],
80
+ fallback: "decimal"
81
+ }
82
+ ];
83
+ for (const { control, kind, styles, fallback } of lists) {
84
+ const base = editor.ui.registry.get(control);
85
+ if (!base || base.type !== "button") continue;
86
+ const { type: _type, ...button } = base;
87
+ void _type;
88
+ editor.ui.registry.addSplitButton(control, {
89
+ ...button,
90
+ items: (e) => {
91
+ const list = findList(e.view.state, nodesOf(e.view.state)[kind]);
92
+ const current = list?.attrs.listStyle ?? (list ? fallback : null);
93
+ return styles.map((style) => ({
94
+ id: style,
95
+ label: labels[style],
96
+ active: current === style,
97
+ onSelect: () => applyStyle(e, kind, style, fallback)
98
+ }));
99
+ }
100
+ });
101
+ }
102
+ }
103
+ });
104
+ export {
105
+ advlist_default as default
106
+ };
107
+ //# sourceMappingURL=advlist-FRIJ6LO7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugins/advlist.ts"],"sourcesContent":["import type { NodeType } from 'prosemirror-model';\nimport type { EditorState } from 'prosemirror-state';\nimport { nodesOf } from '../commands';\nimport type { Editor } from '../editor';\nimport { definePlugin } from '../plugins';\nimport { BULLET_STYLES, ORDERED_STYLES } from '../schema';\nimport type { ButtonSpec } from '../ui/registry';\nimport { pickLabels } from './shared';\n\n/**\n * Плагин advlist: стиль маркеров (точка, кружок, квадрат) и нумерации (1, a, A, i, I, α).\n * Кнопки `bullist` и `numlist` становятся составными: основная часть переключает список,\n * стрелка — выбор стиля. `plugins: ['advlist']`; наборы стилей — `pluginOptions.advlist`\n * (`bullets`, `numbers`, как advlist_bullet_styles / advlist_number_styles).\n */\n\nexport interface AdvlistOptions {\n bullets?: (typeof BULLET_STYLES)[number][];\n numbers?: (typeof ORDERED_STYLES)[number][];\n}\n\nconst LABELS = {\n en: {\n disc: 'Default',\n circle: 'Circle',\n square: 'Square',\n decimal: 'Default (1, 2, 3)',\n 'lower-alpha': 'Lower alpha (a, b, c)',\n 'upper-alpha': 'Upper alpha (A, B, C)',\n 'lower-roman': 'Lower roman (i, ii, iii)',\n 'upper-roman': 'Upper roman (I, II, III)',\n 'lower-greek': 'Lower greek (α, β, γ)',\n },\n ru: {\n disc: 'По умолчанию',\n circle: 'Кружок',\n square: 'Квадрат',\n decimal: 'По умолчанию (1, 2, 3)',\n 'lower-alpha': 'Строчные буквы (a, b, c)',\n 'upper-alpha': 'Прописные буквы (A, B, C)',\n 'lower-roman': 'Римские строчные (i, ii, iii)',\n 'upper-roman': 'Римские прописные (I, II, III)',\n 'lower-greek': 'Греческие (α, β, γ)',\n },\n};\n\n/** Ближайший список нужного типа вокруг выделения. */\nfunction findList(\n state: EditorState,\n type: NodeType,\n): { pos: number; attrs: Record<string, unknown> } | null {\n const { $from } = state.selection;\n for (let depth = $from.depth; depth > 0; depth--) {\n const node = $from.node(depth);\n if (node.type === type) return { pos: $from.before(depth), attrs: node.attrs };\n }\n return null;\n}\n\nfunction applyStyle(\n editor: Editor,\n kind: 'bullet_list' | 'ordered_list',\n style: string,\n fallback: string,\n): void {\n const type = () => nodesOf(editor.view.state)[kind];\n // Не в списке этого типа — сначала создаём список, потом задаём стиль.\n if (!findList(editor.view.state, type()))\n editor.exec(kind === 'bullet_list' ? 'bulletList' : 'orderedList');\n const list = findList(editor.view.state, type());\n if (!list) return;\n const { state, dispatch } = editor.view;\n dispatch(\n state.tr.setNodeMarkup(list.pos, undefined, {\n ...list.attrs,\n listStyle: style === fallback ? null : style,\n }),\n );\n editor.focus();\n}\n\nexport default definePlugin({\n name: 'advlist',\n setup(editor) {\n const labels = pickLabels(editor, LABELS);\n const options = (editor.options.pluginOptions?.advlist ?? {}) as AdvlistOptions;\n const lists = [\n {\n control: 'bullist',\n kind: 'bullet_list',\n styles: options.bullets ?? [...BULLET_STYLES],\n fallback: 'disc',\n },\n {\n control: 'numlist',\n kind: 'ordered_list',\n styles: options.numbers ?? [...ORDERED_STYLES],\n fallback: 'decimal',\n },\n ] as const;\n\n for (const { control, kind, styles, fallback } of lists) {\n const base = editor.ui.registry.get(control) as ButtonSpec | undefined;\n if (!base || base.type !== 'button') continue;\n const { type: _type, ...button } = base;\n void _type;\n editor.ui.registry.addSplitButton(control, {\n ...button,\n items: (e) => {\n const list = findList(e.view.state, nodesOf(e.view.state)[kind]);\n const current = (list?.attrs.listStyle as string | null) ?? (list ? fallback : null);\n return styles.map((style) => ({\n id: style,\n label: labels[style],\n active: current === style,\n onSelect: () => applyStyle(e, kind, style, fallback),\n }));\n },\n });\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,IAAM,SAAS;AAAA,EACb,IAAI;AAAA,IACF,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,eAAe;AAAA,IACf,eAAe;AAAA,IACf,eAAe;AAAA,IACf,eAAe;AAAA,IACf,eAAe;AAAA,EACjB;AAAA,EACA,IAAI;AAAA,IACF,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,eAAe;AAAA,IACf,eAAe;AAAA,IACf,eAAe;AAAA,IACf,eAAe;AAAA,IACf,eAAe;AAAA,EACjB;AACF;AAGA,SAAS,SACP,OACA,MACwD;AACxD,QAAM,EAAE,MAAM,IAAI,MAAM;AACxB,WAAS,QAAQ,MAAM,OAAO,QAAQ,GAAG,SAAS;AAChD,UAAM,OAAO,MAAM,KAAK,KAAK;AAC7B,QAAI,KAAK,SAAS,KAAM,QAAO,EAAE,KAAK,MAAM,OAAO,KAAK,GAAG,OAAO,KAAK,MAAM;AAAA,EAC/E;AACA,SAAO;AACT;AAEA,SAAS,WACP,QACA,MACA,OACA,UACM;AACN,QAAM,OAAO,MAAM,QAAQ,OAAO,KAAK,KAAK,EAAE,IAAI;AAElD,MAAI,CAAC,SAAS,OAAO,KAAK,OAAO,KAAK,CAAC;AACrC,WAAO,KAAK,SAAS,gBAAgB,eAAe,aAAa;AACnE,QAAM,OAAO,SAAS,OAAO,KAAK,OAAO,KAAK,CAAC;AAC/C,MAAI,CAAC,KAAM;AACX,QAAM,EAAE,OAAO,SAAS,IAAI,OAAO;AACnC;AAAA,IACE,MAAM,GAAG,cAAc,KAAK,KAAK,QAAW;AAAA,MAC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0 +1,89 @@
1
+ import {
2
+ isSafeLinkUrl,
3
+ marksOf
4
+ } from "./chunk-GHEFKKRC.js";
5
+ import {
6
+ definePlugin
7
+ } from "./chunk-F6TSOU5U.js";
8
+
9
+ // src/plugins/autolink.ts
10
+ import { InputRule, inputRules } from "prosemirror-inputrules";
11
+ import { Plugin, Selection } from "prosemirror-state";
12
+ var URL_AT_END = /(?:^|[\s(])((?:https?:\/\/|www\.)[^\s<>"]*[^\s<>".,;:!?)\]'"]|[\w.+-]+@[\w-]+(?:\.[\w-]+)+)([.,;:!?)\]'"]*)$/i;
13
+ var SINGLE_URL = /^(?:https?:\/\/|www\.)\S+$|^mailto:\S+$/i;
14
+ function toHref(text) {
15
+ if (/^www\./i.test(text)) return `https://${text}`;
16
+ if (/^[\w.+-]+@/.test(text)) return `mailto:${text}`;
17
+ return text;
18
+ }
19
+ function linkifyBefore(state, tr, end) {
20
+ const $end = state.doc.resolve(end);
21
+ if (!$end.parent.isTextblock || $end.parent.type.spec.code) return false;
22
+ const textBefore = $end.parent.textBetween(0, $end.parentOffset, void 0, "\uFFFC");
23
+ const match = textBefore.match(URL_AT_END);
24
+ if (!match) return false;
25
+ const text = match[1];
26
+ const to = end - match[2].length;
27
+ const from = to - text.length;
28
+ const link = marksOf(state).link;
29
+ if (state.doc.rangeHasMark(from, to, link)) return false;
30
+ const href = toHref(text);
31
+ if (!isSafeLinkUrl(href)) return false;
32
+ tr.addMark(from, to, link.create({ href }));
33
+ return true;
34
+ }
35
+ var autolink_default = definePlugin({
36
+ name: "autolink",
37
+ prosemirrorPlugins: (editor) => [
38
+ inputRules({
39
+ rules: [
40
+ // Пробел после адреса: оформляем адрес ссылкой и вставляем сам пробел.
41
+ new InputRule(/\S\s$/, (state, match, start, end) => {
42
+ if (!editor.isAllowed("link")) return null;
43
+ const tr = state.tr;
44
+ const urlEnd = start + match[0].length - 1;
45
+ if (!linkifyBefore(state, tr, urlEnd)) return null;
46
+ return tr.insertText(match[0].slice(-1), end).removeStoredMark(marksOf(state).link);
47
+ })
48
+ ]
49
+ }),
50
+ new Plugin({
51
+ /**
52
+ * Enter после адреса. Раскладка клавиш ядра обрабатывает Enter раньше плагинов, поэтому смотрим
53
+ * на результат: курсор в начале нового блока, а предыдущий блок заканчивается адресом.
54
+ */
55
+ appendTransaction(transactions, _old, state) {
56
+ if (!editor.isAllowed("link") || !transactions.some((tr2) => tr2.docChanged)) return null;
57
+ const { $from, empty } = state.selection;
58
+ if (!empty || $from.parentOffset !== 0 || $from.depth < 1) return null;
59
+ const prev = Selection.findFrom(state.doc.resolve($from.before()), -1, true);
60
+ if (!prev || !prev.empty || prev.$from.parentOffset !== prev.$from.parent.content.size)
61
+ return null;
62
+ const tr = state.tr;
63
+ return linkifyBefore(state, tr, prev.from) ? tr : null;
64
+ }
65
+ }),
66
+ new Plugin({
67
+ props: {
68
+ handlePaste(view, event) {
69
+ const { state } = view;
70
+ if (state.selection.empty || !editor.isAllowed("link")) return false;
71
+ const text = (event.clipboardData?.getData("text/plain") ?? "").trim();
72
+ if (!SINGLE_URL.test(text)) return false;
73
+ const href = toHref(text);
74
+ if (!isSafeLinkUrl(href)) return false;
75
+ const { from, to } = state.selection;
76
+ const link = marksOf(state).link;
77
+ view.dispatch(
78
+ state.tr.removeMark(from, to, link).addMark(from, to, link.create({ href }))
79
+ );
80
+ return true;
81
+ }
82
+ }
83
+ })
84
+ ]
85
+ });
86
+ export {
87
+ autolink_default as default
88
+ };
89
+ //# sourceMappingURL=autolink-ZVHNOOS7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugins/autolink.ts"],"sourcesContent":["import { InputRule, inputRules } from 'prosemirror-inputrules';\nimport type { EditorState, Transaction } from 'prosemirror-state';\nimport { Plugin, Selection } from 'prosemirror-state';\nimport { marksOf } from '../commands';\nimport { definePlugin } from '../plugins';\nimport { isSafeLinkUrl } from '../url';\n\n/**\n * Плагин autolink:\n * - адрес или e-mail становится ссылкой, когда после него набран пробел или нажат Enter;\n * - вставка адреса поверх выделенного текста делает этот текст ссылкой (как в Google Docs).\n * `plugins: ['autolink']`.\n */\n\n// Адрес в конце текста (группа 1) и завершающая пунктуация после него (группа 2): «см. https://x.com.» —\n// точка в ссылку не входит.\nconst URL_AT_END =\n /(?:^|[\\s(])((?:https?:\\/\\/|www\\.)[^\\s<>\"]*[^\\s<>\".,;:!?)\\]'\"]|[\\w.+-]+@[\\w-]+(?:\\.[\\w-]+)+)([.,;:!?)\\]'\"]*)$/i;\nconst SINGLE_URL = /^(?:https?:\\/\\/|www\\.)\\S+$|^mailto:\\S+$/i;\n\nfunction toHref(text: string): string {\n if (/^www\\./i.test(text)) return `https://${text}`;\n if (/^[\\w.+-]+@/.test(text)) return `mailto:${text}`;\n return text;\n}\n\n/** Сделать ссылкой адрес, заканчивающийся в позиции end (если он есть и ещё не ссылка). */\nfunction linkifyBefore(state: EditorState, tr: Transaction, end: number): boolean {\n const $end = state.doc.resolve(end);\n if (!$end.parent.isTextblock || $end.parent.type.spec.code) return false;\n const textBefore = $end.parent.textBetween(0, $end.parentOffset, undefined, '');\n const match = textBefore.match(URL_AT_END);\n if (!match) return false;\n const text = match[1]!;\n const to = end - match[2]!.length;\n const from = to - text.length;\n const link = marksOf(state).link;\n if (state.doc.rangeHasMark(from, to, link)) return false;\n const href = toHref(text);\n if (!isSafeLinkUrl(href)) return false;\n tr.addMark(from, to, link.create({ href }));\n return true;\n}\n\nexport default definePlugin({\n name: 'autolink',\n prosemirrorPlugins: (editor) => [\n inputRules({\n rules: [\n // Пробел после адреса: оформляем адрес ссылкой и вставляем сам пробел.\n new InputRule(/\\S\\s$/, (state, match, start, end) => {\n if (!editor.isAllowed('link')) return null;\n const tr = state.tr;\n const urlEnd = start + match[0].length - 1;\n if (!linkifyBefore(state, tr, urlEnd)) return null;\n return tr.insertText(match[0].slice(-1), end).removeStoredMark(marksOf(state).link);\n }),\n ],\n }),\n new Plugin({\n /**\n * Enter после адреса. Раскладка клавиш ядра обрабатывает Enter раньше плагинов, поэтому смотрим\n * на результат: курсор в начале нового блока, а предыдущий блок заканчивается адресом.\n */\n appendTransaction(transactions, _old, state) {\n if (!editor.isAllowed('link') || !transactions.some((tr) => tr.docChanged)) return null;\n const { $from, empty } = state.selection;\n if (!empty || $from.parentOffset !== 0 || $from.depth < 1) return null;\n // Конец предыдущего текстового блока — в том числе в соседнем пункте списка или ячейке.\n const prev = Selection.findFrom(state.doc.resolve($from.before()), -1, true);\n if (!prev || !prev.empty || prev.$from.parentOffset !== prev.$from.parent.content.size)\n return null;\n const tr = state.tr;\n return linkifyBefore(state, tr, prev.from) ? tr : null;\n },\n }),\n new Plugin({\n props: {\n handlePaste(view, event) {\n const { state } = view;\n if (state.selection.empty || !editor.isAllowed('link')) return false;\n const text = (event.clipboardData?.getData('text/plain') ?? '').trim();\n if (!SINGLE_URL.test(text)) return false;\n const href = toHref(text);\n if (!isSafeLinkUrl(href)) return false;\n const { from, to } = state.selection;\n const link = marksOf(state).link;\n view.dispatch(\n state.tr.removeMark(from, to, link).addMark(from, to, link.create({ href })),\n );\n return true;\n },\n },\n }),\n ],\n});\n"],"mappings":";;;;;;;;;AAAA,SAAS,WAAW,kBAAkB;AAEtC,SAAS,QAAQ,iBAAiB;AAclC,IAAM,aACJ;AACF,IAAM,aAAa;AAEnB,SAAS,OAAO,MAAsB;AACpC,MAAI,UAAU,KAAK,IAAI,EAAG,QAAO,WAAW,IAAI;AAChD,MAAI,aAAa,KAAK,IAAI,EAAG,QAAO,UAAU,IAAI;AAClD,SAAO;AACT;AAGA,SAAS,cAAc,OAAoB,IAAiB,KAAsB;AAChF,QAAM,OAAO,MAAM,IAAI,QAAQ,GAAG;AAClC,MAAI,CAAC,KAAK,OAAO,eAAe,KAAK,OAAO,KAAK,KAAK,KAAM,QAAO;AACnE,QAAM,aAAa,KAAK,OAAO,YAAY,GAAG,KAAK,cAAc,QAAW,QAAG;AAC/E,QAAM,QAAQ,WAAW,MAAM,UAAU;AACzC,MAAI,CAAC,MAAO,QAAO;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AAC,GAAG,IAAI,IAAI;AAC3E,YAAI,CAAC,QAAQ,CAAC,KAAK,SAAS,KAAK,MAAM,iBAAiB,KAAK,MAAM,OAAO,QAAQ;AAChF,iBAAO;AACT,cAAM,KAAK,MAAM;AACjB,eAAO,cAAc,OAAO,IAAI,KAAK,IAAI,IAAI,KAAK;AAAA,MACpD;AAAA,IACF,CAAC;AAAA,IACD,IAAI,OAAO;AAAA,MACT,OAAO;AAAA,QACL,YAAY,MAAM,OAAO;AACvB,gBAAM,EAAE,MAAM,IAAI;AAClB,cAAI,MAAM,UAAU,SAAS,CAAC,OAAO,UAAU,MAAM,EAAG,QAAO;AAC/D,gBAAM,QAAQ,MAAM,eAAe,QAAQ,YAAY,KAAK,IAAI,KAAK;AACrE,cAAI,CAAC,WAAW,KAAK,IAAI,EAAG,QAAO;AACnC,gBAAM,OAAO,OAAO,IAAI;AACxB,cAAI,CAAC,cAAc,IAAI,EAAG,QAAO;AACjC,gBAAM,EAAE,MAAM,GAAG,IAAI,MAAM;AAC3B,gBAAM,OAAO,QAAQ,KAAK,EAAE;AAC5B,eAAK;AAAA,YACH,MAAM,GAAG,WAAW,MAAM,IAAI,IAAI,EAAE,QAAQ,MAAM,IAAI,KAAK,OAAO,EAAE,KAAK,CAAC,CAAC;AAAA,UAC7E;AACA,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF,CAAC;","names":["tr"]}
@@ -0,0 +1,26 @@
1
+ import {
2
+ definePlugin
3
+ } from "./chunk-F6TSOU5U.js";
4
+
5
+ // src/plugins/autoresize.ts
6
+ var autoresize_default = definePlugin({
7
+ name: "autoresize",
8
+ setup(editor) {
9
+ const { minHeight, maxHeight } = editor.options.pluginOptions?.autoresize ?? {};
10
+ const content = editor.root.querySelector(".nova-content");
11
+ if (!content) return;
12
+ editor.root.classList.add("nova-autoresize");
13
+ if (minHeight !== void 0)
14
+ editor.root.style.setProperty("--nova-min-height", `${minHeight}px`);
15
+ if (maxHeight !== void 0) content.style.maxHeight = `${maxHeight}px`;
16
+ return () => {
17
+ editor.root.classList.remove("nova-autoresize");
18
+ editor.root.style.removeProperty("--nova-min-height");
19
+ content.style.removeProperty("max-height");
20
+ };
21
+ }
22
+ });
23
+ export {
24
+ autoresize_default as default
25
+ };
26
+ //# sourceMappingURL=autoresize-WT4ONZKK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugins/autoresize.ts"],"sourcesContent":["import { definePlugin } from '../plugins';\n\n/**\n * Плагин autoresize: высота редактора следует за текстом в пределах minHeight…maxHeight;\n * дальше — прокрутка внутри редактора, а тулбар остаётся на месте.\n * `plugins: ['autoresize']`, `pluginOptions: { autoresize: { minHeight: 200, maxHeight: 600 } }`.\n */\n\nexport interface AutoresizeOptions {\n /** Минимальная высота области текста, px. */\n minHeight?: number;\n /** Максимальная высота области текста, px (по умолчанию — без ограничения). */\n maxHeight?: number;\n}\n\nexport default definePlugin({\n name: 'autoresize',\n setup(editor) {\n const { minHeight, maxHeight } = (editor.options.pluginOptions?.autoresize ??\n {}) as AutoresizeOptions;\n const content = editor.root.querySelector<HTMLElement>('.nova-content');\n if (!content) return;\n editor.root.classList.add('nova-autoresize');\n if (minHeight !== undefined)\n editor.root.style.setProperty('--nova-min-height', `${minHeight}px`);\n if (maxHeight !== undefined) content.style.maxHeight = `${maxHeight}px`;\n return () => {\n editor.root.classList.remove('nova-autoresize');\n editor.root.style.removeProperty('--nova-min-height');\n content.style.removeProperty('max-height');\n };\n },\n});\n"],"mappings":";;;;;AAeA,IAAO,qBAAQ,aAAa;AAAA,EAC1B,MAAM;AAAA,EACN,MAAM,QAAQ;AACZ,UAAM,EAAE,WAAW,UAAU,IAAK,OAAO,QAAQ,eAAe,cAC9D,CAAC;AACH,UAAM,UAAU,OAAO,KAAK,cAA2B,eAAe;AACtE,QAAI,CAAC,QAAS;AACd,WAAO,KAAK,UAAU,IAAI,iBAAiB;AAC3C,QAAI,cAAc;AAChB,aAAO,KAAK,MAAM,YAAY,qBAAqB,GAAG,SAAS,IAAI;AACrE,QAAI,cAAc,OAAW,SAAQ,MAAM,YAAY,GAAG,SAAS;AACnE,WAAO,MAAM;AACX,aAAO,KAAK,UAAU,OAAO,iBAAiB;AAC9C,aAAO,KAAK,MAAM,eAAe,mBAAmB;AACpD,cAAQ,MAAM,eAAe,YAAY;AAAA,IAC3C;AAAA,EACF;AACF,CAAC;","names":[]}
@@ -0,0 +1,99 @@
1
+ import {
2
+ pickLabels
3
+ } from "./chunk-6RJENZXT.js";
4
+ import "./chunk-HZRIBOPW.js";
5
+ import {
6
+ definePlugin
7
+ } from "./chunk-F6TSOU5U.js";
8
+
9
+ // src/plugins/autosave.ts
10
+ var ICON = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l3 2"/></svg>';
11
+ var LABELS = {
12
+ en: {
13
+ restore: "Restore last draft",
14
+ found: "An unsaved draft was found. Use \u201CRestore last draft\u201D to bring it back.",
15
+ restored: "Draft restored"
16
+ },
17
+ ru: {
18
+ restore: "\u0412\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0447\u0435\u0440\u043D\u043E\u0432\u0438\u043A",
19
+ found: "\u041D\u0430\u0439\u0434\u0435\u043D \u043D\u0435\u0441\u043E\u0445\u0440\u0430\u043D\u0451\u043D\u043D\u044B\u0439 \u0447\u0435\u0440\u043D\u043E\u0432\u0438\u043A. \u0415\u0433\u043E \u043C\u043E\u0436\u043D\u043E \u0432\u0435\u0440\u043D\u0443\u0442\u044C \u043A\u043D\u043E\u043F\u043A\u043E\u0439 \xAB\u0412\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0447\u0435\u0440\u043D\u043E\u0432\u0438\u043A\xBB.",
20
+ restored: "\u0427\u0435\u0440\u043D\u043E\u0432\u0438\u043A \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D"
21
+ }
22
+ };
23
+ function storage() {
24
+ try {
25
+ return typeof localStorage === "undefined" ? null : localStorage;
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+ var autosave_default = definePlugin({
31
+ name: "autosave",
32
+ toolbar: "restoredraft",
33
+ setup(editor) {
34
+ const options = editor.options.pluginOptions?.autosave ?? {};
35
+ const labels = pickLabels(editor, LABELS);
36
+ const store = storage();
37
+ const key = options.key ?? `novaprose-draft:${typeof location === "undefined" ? "" : location.pathname}:${editor.options.element.id || "editor"}`;
38
+ const delay = options.delay ?? 1e3;
39
+ const retentionMs = (options.retention ?? 7 * 24 * 60) * 6e4;
40
+ const read = () => {
41
+ try {
42
+ const draft = JSON.parse(store?.getItem(key) ?? "null");
43
+ if (!draft || typeof draft.html !== "string" || Date.now() - draft.time > retentionMs)
44
+ return null;
45
+ return draft;
46
+ } catch {
47
+ return null;
48
+ }
49
+ };
50
+ let pending = read();
51
+ if (pending && pending.html === editor.getHTML()) pending = null;
52
+ if (pending) editor.ui.notify({ text: labels.found, timeout: 8e3 });
53
+ let timer;
54
+ const save = () => {
55
+ timer = void 0;
56
+ try {
57
+ if (editor.isEmpty()) store?.removeItem(key);
58
+ else store?.setItem(key, JSON.stringify({ html: editor.getHTML(), time: Date.now() }));
59
+ } catch {
60
+ }
61
+ };
62
+ const off = editor.on("change", () => {
63
+ pending = null;
64
+ clearTimeout(timer);
65
+ timer = setTimeout(save, delay);
66
+ });
67
+ const restore = () => {
68
+ const draft = pending ?? read();
69
+ if (!draft) return;
70
+ editor.setContent(draft.html);
71
+ pending = null;
72
+ editor.ui.notify({ text: labels.restored });
73
+ editor.focus();
74
+ };
75
+ const spec = {
76
+ icon: ICON,
77
+ tooltip: labels.restore,
78
+ isEnabled: () => editor.isEditable() && pending !== null,
79
+ onAction: restore
80
+ };
81
+ editor.ui.registry.addButton("restoredraft", spec);
82
+ editor.ui.registry.addMenuItem("restoredraft", {
83
+ text: labels.restore,
84
+ icon: ICON,
85
+ onAction: restore
86
+ });
87
+ return () => {
88
+ off();
89
+ if (timer !== void 0) {
90
+ clearTimeout(timer);
91
+ save();
92
+ }
93
+ };
94
+ }
95
+ });
96
+ export {
97
+ autosave_default as default
98
+ };
99
+ //# sourceMappingURL=autosave-2KI5WGV5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugins/autosave.ts"],"sourcesContent":["import { definePlugin } from '../plugins';\nimport { pickLabels } from './shared';\n\n/**\n * Плагин autosave: черновик в localStorage браузера, чтобы текст не пропал при закрытой вкладке,\n * перезагрузке или сбое. Если при открытии найден черновик, отличный от текущего содержимого,\n * появляется уведомление, а кнопка «Восстановить черновик» (restoredraft) становится активной.\n *\n * `plugins: ['autosave']`, настройки — `pluginOptions.autosave`:\n * - key — ключ хранилища (по умолчанию адрес страницы + id элемента);\n * - delay — задержка сохранения после изменения, мс (1000);\n * - retention — сколько хранить черновик, минут (7 дней).\n */\n\nexport interface AutosaveOptions {\n key?: string;\n delay?: number;\n retention?: number;\n}\n\ninterface Draft {\n html: string;\n time: number;\n}\n\nconst ICON =\n '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M3 12a9 9 0 1 0 3-6.7L3 8\"/><path d=\"M3 3v5h5\"/><path d=\"M12 7v5l3 2\"/></svg>';\n\nconst LABELS = {\n en: {\n restore: 'Restore last draft',\n found: 'An unsaved draft was found. Use “Restore last draft” to bring it back.',\n restored: 'Draft restored',\n },\n ru: {\n restore: 'Восстановить черновик',\n found: 'Найден несохранённый черновик. Его можно вернуть кнопкой «Восстановить черновик».',\n restored: 'Черновик восстановлен',\n },\n};\n\nfunction storage(): Storage | null {\n try {\n return typeof localStorage === 'undefined' ? null : localStorage;\n } catch {\n // Доступ к localStorage запрещён (приватный режим, политика браузера) — работаем без черновиков.\n return null;\n }\n}\n\nexport default definePlugin({\n name: 'autosave',\n toolbar: 'restoredraft',\n setup(editor) {\n const options = (editor.options.pluginOptions?.autosave ?? {}) as AutosaveOptions;\n const labels = pickLabels(editor, LABELS);\n const store = storage();\n const key =\n options.key ??\n `novaprose-draft:${typeof location === 'undefined' ? '' : location.pathname}:${editor.options.element.id || 'editor'}`;\n const delay = options.delay ?? 1000;\n const retentionMs = (options.retention ?? 7 * 24 * 60) * 60_000;\n\n const read = (): Draft | null => {\n try {\n const draft = JSON.parse(store?.getItem(key) ?? 'null') as Draft | null;\n if (!draft || typeof draft.html !== 'string' || Date.now() - draft.time > retentionMs)\n return null;\n return draft;\n } catch {\n return null;\n }\n };\n\n // Черновик с прошлого раза запоминаем до первого сохранения нового.\n let pending = read();\n if (pending && pending.html === editor.getHTML()) pending = null;\n if (pending) editor.ui.notify({ text: labels.found, timeout: 8000 });\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const save = () => {\n timer = undefined;\n try {\n if (editor.isEmpty()) store?.removeItem(key);\n else store?.setItem(key, JSON.stringify({ html: editor.getHTML(), time: Date.now() }));\n } catch {\n // Хранилище переполнено — не мешаем работе.\n }\n };\n const off = editor.on('change', () => {\n // Первое изменение после открытия — старый черновик больше не восстанавливаем поверх.\n pending = null;\n clearTimeout(timer);\n timer = setTimeout(save, delay);\n });\n\n const restore = () => {\n const draft = pending ?? read();\n if (!draft) return;\n editor.setContent(draft.html);\n pending = null;\n editor.ui.notify({ text: labels.restored });\n editor.focus();\n };\n const spec = {\n icon: ICON,\n tooltip: labels.restore,\n isEnabled: () => editor.isEditable() && pending !== null,\n onAction: restore,\n };\n editor.ui.registry.addButton('restoredraft', spec);\n editor.ui.registry.addMenuItem('restoredraft', {\n text: labels.restore,\n icon: ICON,\n onAction: restore,\n });\n\n return () => {\n off();\n // Изменения последней секунды не теряем.\n if (timer !== undefined) {\n clearTimeout(timer);\n save();\n }\n };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