@novaprose/core 0.2.0 → 0.4.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 (43) hide show
  1. package/dist/{advlist-FRIJ6LO7.js → advlist-FH3K3AAQ.js} +5 -5
  2. package/dist/{autolink-ZVHNOOS7.js → autolink-IDJWAL2V.js} +2 -2
  3. package/dist/{autoresize-WT4ONZKK.js → autoresize-4ZEPQCHP.js} +2 -2
  4. package/dist/{autosave-2KI5WGV5.js → autosave-WODRZ7L6.js} +2 -2
  5. package/dist/{charmap-3LM5LZCC.js → charmap-LWA7TL3K.js} +2 -2
  6. package/dist/chunk-2A3IYKPE.js +5047 -0
  7. package/dist/chunk-2A3IYKPE.js.map +1 -0
  8. package/dist/{chunk-F6TSOU5U.js → chunk-6GWG2BLC.js} +1 -1
  9. package/dist/chunk-6GWG2BLC.js.map +1 -0
  10. package/dist/{chunk-AGBQEZ2U.js → chunk-PHRON5PL.js} +7 -7
  11. package/dist/chunk-Z3ELZ77W.js +102 -0
  12. package/dist/chunk-Z3ELZ77W.js.map +1 -0
  13. package/dist/comments-panel-FYJE3U64.js +464 -0
  14. package/dist/comments-panel-FYJE3U64.js.map +1 -0
  15. package/dist/{directionality-VSDWPWHX.js → directionality-N62ZB7CF.js} +5 -5
  16. package/dist/{emoticons-YVGVA76P.js → emoticons-WQ3K4J6G.js} +2 -2
  17. package/dist/index.cjs +6948 -4743
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +423 -7
  20. package/dist/index.d.ts +423 -7
  21. package/dist/index.js +1001 -4980
  22. package/dist/index.js.map +1 -1
  23. package/dist/{insertdatetime-QYWZUYO4.js → insertdatetime-2RZ3UUQE.js} +2 -2
  24. package/dist/{nonbreaking-SIACL5V6.js → nonbreaking-L6GNDHVO.js} +2 -2
  25. package/dist/{quickbars-WW3TGVCS.js → quickbars-TIRY3RH4.js} +4 -4
  26. package/dist/revisionhistory-GDTOULKS.js +457 -0
  27. package/dist/revisionhistory-GDTOULKS.js.map +1 -0
  28. package/dist/{visualblocks-WB6NAEGB.js → visualblocks-V4CQ4XMF.js} +2 -2
  29. package/package.json +1 -1
  30. package/src/style.css +502 -0
  31. package/dist/chunk-F6TSOU5U.js.map +0 -1
  32. /package/dist/{advlist-FRIJ6LO7.js.map → advlist-FH3K3AAQ.js.map} +0 -0
  33. /package/dist/{autolink-ZVHNOOS7.js.map → autolink-IDJWAL2V.js.map} +0 -0
  34. /package/dist/{autoresize-WT4ONZKK.js.map → autoresize-4ZEPQCHP.js.map} +0 -0
  35. /package/dist/{autosave-2KI5WGV5.js.map → autosave-WODRZ7L6.js.map} +0 -0
  36. /package/dist/{charmap-3LM5LZCC.js.map → charmap-LWA7TL3K.js.map} +0 -0
  37. /package/dist/{chunk-AGBQEZ2U.js.map → chunk-PHRON5PL.js.map} +0 -0
  38. /package/dist/{directionality-VSDWPWHX.js.map → directionality-N62ZB7CF.js.map} +0 -0
  39. /package/dist/{emoticons-YVGVA76P.js.map → emoticons-WQ3K4J6G.js.map} +0 -0
  40. /package/dist/{insertdatetime-QYWZUYO4.js.map → insertdatetime-2RZ3UUQE.js.map} +0 -0
  41. /package/dist/{nonbreaking-SIACL5V6.js.map → nonbreaking-L6GNDHVO.js.map} +0 -0
  42. /package/dist/{quickbars-WW3TGVCS.js.map → quickbars-TIRY3RH4.js.map} +0 -0
  43. /package/dist/{visualblocks-WB6NAEGB.js.map → visualblocks-V4CQ4XMF.js.map} +0 -0
@@ -77,4 +77,4 @@ export {
77
77
  orderPlugins,
78
78
  loadPlugin
79
79
  };
80
- //# sourceMappingURL=chunk-F6TSOU5U.js.map
80
+ //# sourceMappingURL=chunk-6GWG2BLC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugins.ts"],"sourcesContent":["import type { MarkSpec, NodeSpec } from 'prosemirror-model';\nimport type { Command, EditorState, Plugin as PMPlugin, Transaction } from 'prosemirror-state';\nimport type { CommandName } from './commands';\nimport type { Editor } from './editor';\n\n/**\n * Плагин NovaProse. Встроенные и сторонние плагины используют один и тот же API.\n *\n * ```ts\n * export default definePlugin({\n * name: 'signature',\n * setup(editor) {\n * editor.ui.registry.addButton('signature', { text: 'Подпись', tooltip: '…', onAction: … });\n * },\n * });\n * ```\n */\nexport interface NovaPlugin {\n /** Уникальное имя; по нему плагин указывается в конфиге и в requires других плагинов. */\n name: string;\n /** Плагины, которые должны быть подключены раньше. */\n requires?: string[];\n /** Регистрация кнопок, команд, автокомплитеров. Может вернуть функцию очистки (при destroy). */\n setup?: (editor: Editor) => void | (() => void);\n /**\n * Кнопки, которые добавляются в конец тулбара по умолчанию ('insertdatetime').\n * Если пользователь задал свой toolbar — не добавляются: его конфиг главнее.\n */\n toolbar?: string;\n /** ProseMirror-плагины (ввод, декорации, клавиши). */\n prosemirrorPlugins?: (editor: Editor) => PMPlugin[];\n /**\n * Новые узлы документа (с parseDOM и toDOM). Расширяют схему конкретного редактора.\n * Плагин с узлами или марками передаётся объектом, не ленивым загрузчиком: схема создаётся сразу.\n */\n nodes?: Record<string, NodeSpec>;\n /** Новые марки (инлайн-форматирование) с parseDOM и toDOM. */\n marks?: Record<string, MarkSpec>;\n /**\n * Переопределение именованных команд (кнопки, меню, горячие клавиши и editor.exec берут их отсюда).\n * Например, совместное редактирование заменяет undo/redo своими — «отменить только свои правки».\n */\n commands?: Partial<Record<CommandName, Command>>;\n /** Плагин ведёт свою историю изменений — встроенная (prosemirror-history) не подключается. */\n replaceHistory?: boolean;\n /**\n * Переписать транзакцию до применения (режим правок превращает удаление в пометку «удалено»).\n * Вызывается для каждой транзакции редактора; вернуть ту же, если менять нечего.\n */\n transformTransaction?: (tr: Transaction, state: EditorState, editor: Editor) => Transaction;\n}\n\ntype Loader = () => Promise<NovaPlugin | { default: NovaPlugin }>;\n\n/** Элемент конфига plugins: объект, имя из реестра или ленивый загрузчик. */\nexport type PluginEntry = NovaPlugin | string | Loader;\n\n/** Помощник для типизации определения плагина. */\nexport function definePlugin(plugin: NovaPlugin): NovaPlugin {\n return plugin;\n}\n\n// ---------- глобальный реестр (аналог PluginManager.add) ----------\n\nconst registry = new Map<string, NovaPlugin | Loader>();\n\n/** Зарегистрировать плагин (или его ленивый загрузчик) под именем — для `plugins: ['имя']`. */\nexport function registerPlugin(name: string, plugin: NovaPlugin | Loader): void {\n registry.set(name, plugin);\n}\n\nexport function isPluginRegistered(name: string): boolean {\n return registry.has(name);\n}\n\n// ---------- разрешение конфига ----------\n\nexport interface ResolvedPlugins {\n /** Синхронные плагины в порядке зависимостей. */\n plugins: NovaPlugin[];\n /** Ленивые загрузчики (грузятся после создания редактора). */\n loaders: Loader[];\n errors: string[];\n}\n\nfunction isLoader(entry: unknown): entry is Loader {\n return typeof entry === 'function';\n}\n\n/** Превращает конфиг в список: имена — из реестра, загрузчики — отдельно. */\nexport function resolveEntries(entries: PluginEntry[]): ResolvedPlugins {\n const plugins: NovaPlugin[] = [];\n const loaders: Loader[] = [];\n const errors: string[] = [];\n for (const entry of entries) {\n if (typeof entry === 'string') {\n const found = registry.get(entry);\n if (!found) errors.push(`Plugin \"${entry}\" is not registered`);\n else if (isLoader(found)) loaders.push(found);\n else plugins.push(found);\n } else if (isLoader(entry)) {\n loaders.push(entry);\n } else {\n plugins.push(entry);\n }\n }\n return { plugins, loaders, errors };\n}\n\n/**\n * Упорядочить по зависимостям (топологическая сортировка).\n * Плагин с отсутствующей или циклической зависимостью исключается, остальные работают.\n * available — имена уже подключённых плагинов (для догружаемых).\n */\nexport function orderPlugins(\n plugins: NovaPlugin[],\n available: Set<string> = new Set(),\n): { ordered: NovaPlugin[]; errors: string[] } {\n const byName = new Map(plugins.map((p) => [p.name, p]));\n const ordered: NovaPlugin[] = [];\n const errors: string[] = [];\n const state = new Map<string, 'visiting' | 'done' | 'failed'>();\n\n const visit = (plugin: NovaPlugin, path: string[]): boolean => {\n const s = state.get(plugin.name);\n if (s === 'done') return true;\n if (s === 'failed') return false;\n if (s === 'visiting') {\n errors.push(`Plugin dependency cycle: ${[...path, plugin.name].join(' → ')}`);\n return false;\n }\n state.set(plugin.name, 'visiting');\n for (const dep of plugin.requires ?? []) {\n if (available.has(dep)) continue;\n const depPlugin = byName.get(dep);\n if (!depPlugin) {\n errors.push(`Plugin \"${plugin.name}\" requires \"${dep}\", which is not loaded`);\n state.set(plugin.name, 'failed');\n return false;\n }\n if (!visit(depPlugin, [...path, plugin.name])) {\n state.set(plugin.name, 'failed');\n return false;\n }\n }\n state.set(plugin.name, 'done');\n ordered.push(plugin);\n return true;\n };\n\n for (const plugin of plugins) visit(plugin, []);\n return { ordered, errors };\n}\n\nexport async function loadPlugin(loader: Loader): Promise<NovaPlugin> {\n const mod = await loader();\n return 'default' in mod && mod.default ? mod.default : (mod as NovaPlugin);\n}\n"],"mappings":";AA0DO,SAAS,aAAa,QAAgC;AAC3D,SAAO;AACT;AAIA,IAAM,WAAW,oBAAI,IAAiC;AAG/C,SAAS,eAAe,MAAc,QAAmC;AAC9E,WAAS,IAAI,MAAM,MAAM;AAC3B;AAEO,SAAS,mBAAmB,MAAuB;AACxD,SAAO,SAAS,IAAI,IAAI;AAC1B;AAYA,SAAS,SAAS,OAAiC;AACjD,SAAO,OAAO,UAAU;AAC1B;AAGO,SAAS,eAAe,SAAyC;AACtE,QAAM,UAAwB,CAAC;AAC/B,QAAM,UAAoB,CAAC;AAC3B,QAAM,SAAmB,CAAC;AAC1B,aAAW,SAAS,SAAS;AAC3B,QAAI,OAAO,UAAU,UAAU;AAC7B,YAAM,QAAQ,SAAS,IAAI,KAAK;AAChC,UAAI,CAAC,MAAO,QAAO,KAAK,WAAW,KAAK,qBAAqB;AAAA,eACpD,SAAS,KAAK,EAAG,SAAQ,KAAK,KAAK;AAAA,UACvC,SAAQ,KAAK,KAAK;AAAA,IACzB,WAAW,SAAS,KAAK,GAAG;AAC1B,cAAQ,KAAK,KAAK;AAAA,IACpB,OAAO;AACL,cAAQ,KAAK,KAAK;AAAA,IACpB;AAAA,EACF;AACA,SAAO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I,UAAU,IAAI,UAAW;AAC1D;","names":[]}
@@ -2,6 +2,12 @@ import {
2
2
  cssValue,
3
3
  schema
4
4
  } from "./chunk-YZPJQB3I.js";
5
+ import {
6
+ FOCUSABLE,
7
+ h,
8
+ icon,
9
+ uniqueId
10
+ } from "./chunk-HZRIBOPW.js";
5
11
  import {
6
12
  getLinkAt,
7
13
  insertImage,
@@ -11,12 +17,6 @@ import {
11
17
  marksOf,
12
18
  nodesOf
13
19
  } from "./chunk-GHEFKKRC.js";
14
- import {
15
- FOCUSABLE,
16
- h,
17
- icon,
18
- uniqueId
19
- } from "./chunk-HZRIBOPW.js";
20
20
 
21
21
  // src/ui/icons.ts
22
22
  var svg = (body) => `<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">${body}</svg>`;
@@ -1065,4 +1065,4 @@ export {
1065
1065
  getCellProps,
1066
1066
  setCellProps
1067
1067
  };
1068
- //# sourceMappingURL=chunk-AGBQEZ2U.js.map
1068
+ //# sourceMappingURL=chunk-PHRON5PL.js.map
@@ -0,0 +1,102 @@
1
+ // src/comments.ts
2
+ var COMMENT_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
3
+ var COMMENT_MAX_LENGTH = 5e3;
4
+ var COMMENT_NAME_MAX_LENGTH = 80;
5
+ function newCommentId(prefix = "c") {
6
+ const bytes = new Uint8Array(9);
7
+ globalThis.crypto.getRandomValues(bytes);
8
+ return prefix + Array.from(bytes, (b) => (b % 36).toString(36)).join("");
9
+ }
10
+ function sanitizeThread(value) {
11
+ if (!value || typeof value !== "object") return null;
12
+ const raw = value;
13
+ if (typeof raw.id !== "string" || !COMMENT_ID_RE.test(raw.id)) return null;
14
+ const comments = Array.isArray(raw.comments) ? raw.comments.map(sanitizeComment).filter((c) => c !== null) : [];
15
+ const resolved = raw.resolved;
16
+ return {
17
+ id: raw.id,
18
+ createdAt: Number(raw.createdAt) || 0,
19
+ comments,
20
+ resolved: resolved && typeof resolved === "object" ? { by: sanitizeAuthor(resolved.by), at: Number(resolved.at) || 0 } : null
21
+ };
22
+ }
23
+ function sanitizeAuthor(value) {
24
+ const raw = value && typeof value === "object" ? value : {};
25
+ return {
26
+ id: String(raw.id ?? "").slice(0, 128),
27
+ name: String(raw.name ?? "").slice(0, COMMENT_NAME_MAX_LENGTH)
28
+ };
29
+ }
30
+ function sanitizeComment(value) {
31
+ if (!value || typeof value !== "object") return null;
32
+ const raw = value;
33
+ if (typeof raw.id !== "string" || !COMMENT_ID_RE.test(raw.id)) return null;
34
+ const comment = {
35
+ id: raw.id,
36
+ author: sanitizeAuthor(raw.author),
37
+ text: String(raw.text ?? "").slice(0, COMMENT_MAX_LENGTH),
38
+ createdAt: Number(raw.createdAt) || 0
39
+ };
40
+ if (raw.editedAt) comment.editedAt = Number(raw.editedAt) || 0;
41
+ if (Array.isArray(raw.mentions)) {
42
+ const mentions = raw.mentions.slice(0, 20).map(sanitizeAuthor).filter((m) => /^[\w.@:+-]{1,128}$/.test(m.id) && m.name);
43
+ if (mentions.length) comment.mentions = mentions;
44
+ }
45
+ return comment;
46
+ }
47
+ function createCommentStore(initial = [], onChange) {
48
+ let threads = initial.map(sanitizeThread).filter((t) => t !== null);
49
+ const listeners = /* @__PURE__ */ new Set();
50
+ const update = (next) => {
51
+ threads = next;
52
+ onChange?.(threads);
53
+ listeners.forEach((listener) => listener());
54
+ };
55
+ const mapThread = (id, fn) => update(threads.map((thread) => thread.id === id ? fn(thread) : thread));
56
+ return {
57
+ threads: () => threads,
58
+ subscribe(listener) {
59
+ listeners.add(listener);
60
+ return () => listeners.delete(listener);
61
+ },
62
+ createThread(thread) {
63
+ const clean = sanitizeThread(thread);
64
+ if (!clean || threads.some((t) => t.id === clean.id)) return;
65
+ update([...threads, clean]);
66
+ },
67
+ reply(threadId, comment) {
68
+ const clean = sanitizeComment(comment);
69
+ if (clean) mapThread(threadId, (t) => ({ ...t, comments: [...t.comments, clean] }));
70
+ },
71
+ editComment(threadId, commentId, text) {
72
+ mapThread(threadId, (t) => ({
73
+ ...t,
74
+ comments: t.comments.map(
75
+ (c) => c.id === commentId ? { ...c, text: text.slice(0, COMMENT_MAX_LENGTH), editedAt: Date.now() } : c
76
+ )
77
+ }));
78
+ },
79
+ deleteComment(threadId, commentId) {
80
+ mapThread(threadId, (t) => ({
81
+ ...t,
82
+ comments: t.comments.filter((c) => c.id !== commentId)
83
+ }));
84
+ },
85
+ setResolved(threadId, resolved) {
86
+ mapThread(threadId, (t) => ({ ...t, resolved: resolved ?? null }));
87
+ },
88
+ deleteThread(threadId) {
89
+ update(threads.filter((t) => t.id !== threadId));
90
+ }
91
+ };
92
+ }
93
+
94
+ export {
95
+ COMMENT_ID_RE,
96
+ COMMENT_MAX_LENGTH,
97
+ COMMENT_NAME_MAX_LENGTH,
98
+ newCommentId,
99
+ sanitizeThread,
100
+ createCommentStore
101
+ };
102
+ //# sourceMappingURL=chunk-Z3ELZ77W.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/comments.ts"],"sourcesContent":["/**\n * Комментарии к тексту: модель данных и хранилище.\n *\n * Текст документа хранит только якорь — марку `<span data-comment=\"id\">` вокруг обсуждаемого фрагмента.\n * Сами обсуждения (ветки) лежат в хранилище: по умолчанию в памяти (сохраняйте их через `onChange`\n * рядом с HTML), при совместном редактировании — в общем Y.Doc (`collabSession.commentStore()`),\n * или в вашем собственном хранилище с тем же интерфейсом.\n */\n\nexport interface CommentAuthor {\n id: string;\n name: string;\n}\n\nexport interface Comment {\n id: string;\n author: CommentAuthor;\n text: string;\n /** Время создания, мс с 1970 (Date.now()). */\n createdAt: number;\n editedAt?: number;\n /** Упомянутые через «@» (в тексте — «@Имя»): кого уведомить. */\n mentions?: CommentAuthor[];\n}\n\nexport interface CommentThread {\n /** Совпадает с data-comment у фрагмента текста. */\n id: string;\n createdAt: number;\n /** Первый комментарий — суть обсуждения, остальные — ответы. */\n comments: Comment[];\n /** Ветка решена: подсветка в тексте скрывается, обсуждение остаётся в истории. */\n resolved?: { by: CommentAuthor; at: number } | null;\n}\n\n/** Хранилище веток. Методы синхронные: интерфейс обновляется сразу, сохранение — на вашей стороне. */\nexport interface CommentStore {\n /** Снимок всех веток (новый массив после каждого изменения). */\n threads(): readonly CommentThread[];\n /** Подписка на любые изменения (в том числе пришедшие от других участников). Возвращает отписку. */\n subscribe(listener: () => void): () => void;\n createThread(thread: CommentThread): void;\n reply(threadId: string, comment: Comment): void;\n editComment(threadId: string, commentId: string, text: string): void;\n deleteComment(threadId: string, commentId: string): void;\n setResolved(threadId: string, resolved: CommentThread['resolved']): void;\n deleteThread(threadId: string): void;\n}\n\n/** Идентификатор ветки: безопасен в атрибуте и селекторе. */\nexport const COMMENT_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;\n/** Ограничения против случайных (или злонамеренных) гигантских данных. */\nexport const COMMENT_MAX_LENGTH = 5000;\nexport const COMMENT_NAME_MAX_LENGTH = 80;\n\nexport function newCommentId(prefix = 'c'): string {\n const bytes = new Uint8Array(9);\n globalThis.crypto.getRandomValues(bytes);\n return prefix + Array.from(bytes, (b) => (b % 36).toString(36)).join('');\n}\n\n/** Привести данные из внешнего источника (JSON, сеть) к безопасному виду; негодное — отбросить. */\nexport function sanitizeThread(value: unknown): CommentThread | null {\n if (!value || typeof value !== 'object') return null;\n const raw = value as Record<string, unknown>;\n if (typeof raw.id !== 'string' || !COMMENT_ID_RE.test(raw.id)) return null;\n const comments = Array.isArray(raw.comments)\n ? raw.comments.map(sanitizeComment).filter((c): c is Comment => c !== null)\n : [];\n const resolved = raw.resolved as Record<string, unknown> | null | undefined;\n return {\n id: raw.id,\n createdAt: Number(raw.createdAt) || 0,\n comments,\n resolved:\n resolved && typeof resolved === 'object'\n ? { by: sanitizeAuthor(resolved.by), at: Number(resolved.at) || 0 }\n : null,\n };\n}\n\nfunction sanitizeAuthor(value: unknown): CommentAuthor {\n const raw = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>;\n return {\n id: String(raw.id ?? '').slice(0, 128),\n name: String(raw.name ?? '').slice(0, COMMENT_NAME_MAX_LENGTH),\n };\n}\n\nfunction sanitizeComment(value: unknown): Comment | null {\n if (!value || typeof value !== 'object') return null;\n const raw = value as Record<string, unknown>;\n if (typeof raw.id !== 'string' || !COMMENT_ID_RE.test(raw.id)) return null;\n const comment: Comment = {\n id: raw.id,\n author: sanitizeAuthor(raw.author),\n text: String(raw.text ?? '').slice(0, COMMENT_MAX_LENGTH),\n createdAt: Number(raw.createdAt) || 0,\n };\n if (raw.editedAt) comment.editedAt = Number(raw.editedAt) || 0;\n if (Array.isArray(raw.mentions)) {\n const mentions = raw.mentions\n .slice(0, 20)\n .map(sanitizeAuthor)\n .filter((m) => /^[\\w.@:+-]{1,128}$/.test(m.id) && m.name);\n if (mentions.length) comment.mentions = mentions;\n }\n return comment;\n}\n\n/**\n * Хранилище в памяти. `initial` — ветки, сохранённые раньше (из вашего бэкенда), `onChange` — сохранить.\n *\n * ```ts\n * const store = createCommentStore(saved.threads, (threads) => api.saveComments(postId, threads));\n * ```\n */\nexport function createCommentStore(\n initial: readonly unknown[] = [],\n onChange?: (threads: readonly CommentThread[]) => void,\n): CommentStore {\n let threads: readonly CommentThread[] = initial\n .map(sanitizeThread)\n .filter((t): t is CommentThread => t !== null);\n const listeners = new Set<() => void>();\n\n const update = (next: readonly CommentThread[]) => {\n threads = next;\n onChange?.(threads);\n listeners.forEach((listener) => listener());\n };\n const mapThread = (id: string, fn: (thread: CommentThread) => CommentThread) =>\n update(threads.map((thread) => (thread.id === id ? fn(thread) : thread)));\n\n return {\n threads: () => threads,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n createThread(thread) {\n const clean = sanitizeThread(thread);\n if (!clean || threads.some((t) => t.id === clean.id)) return;\n update([...threads, clean]);\n },\n reply(threadId, comment) {\n const clean = sanitizeComment(comment);\n if (clean) mapThread(threadId, (t) => ({ ...t, comments: [...t.comments, clean] }));\n },\n editComment(threadId, commentId, text) {\n mapThread(threadId, (t) => ({\n ...t,\n comments: t.comments.map((c) =>\n c.id === commentId\n ? { ...c, text: text.slice(0, COMMENT_MAX_LENGTH), editedAt: Date.now() }\n : c,\n ),\n }));\n },\n deleteComment(threadId, commentId) {\n mapThread(threadId, (t) => ({\n ...t,\n comments: t.comments.filter((c) => c.id !== commentId),\n }));\n },\n setResolved(threadId, resolved) {\n mapThread(threadId, (t) => ({ ...t, resolved: resolved ?? null }));\n },\n deleteThread(threadId) {\n update(threads.filter((t) => t.id !== threadId));\n },\n };\n}\n"],"mappings":";AAkDO,IAAM,gBAAgB;AAEtB,IAAM,qBAAqB;AAC3B,IAAM,0BAA0B;AAEhC,SAAS,aAAa,SAAS,KAAa;AACjD,QAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,aAAW,OAAO,gBAAgB,KAAK;AACvC,SAAO,SAAS,MAAM,KAAK,OAAO,CAAC,OAAO,IAAI,IAAI,SAAS,EAAE,CAAC,EAAE,KAAK,EAAE;AACzE;AAGO,SAAS,eAAe,OAAsC;AACnE,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,MAAM;AACZ,MAAI,OAAO,IAAI,OAAO,YAAY,CAAC,cAAc,KAAK,IAAI,EAAE,EAAG,QAAO;AACtE,QAAM,WAAW,MAAM,QAAQ,IAAI,QAAQ,IACvC,IAAI,SAAS,IAAI,eAAe,EAAE,OAAO,CAAC,MAAoB,MAAM,IAAI,IACxE,CAAC;AACL,QAAM,WAAW,IAAI;AACrB,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,WAAW,OAAO,IAAI,SAAS,KAAK;AAAA,IACpC;AAAA,IACA,UACE,YAAY,OAAO,aAAa,WAC5B,EAAE,IAAI,eAAe,SAAS,EAAE,GAAG,IAAI,OAAO,SAAS,EAAE,KAAK,EAAE,IAChE;AAAA,EACR;AACF;AAEA,SAAS,eAAe,OAA+B;AACrD,QAAM,MAAO,SAAS,OAAO,UAAU,WA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,464 @@
1
+ import {
2
+ COMMENT_MAX_LENGTH
3
+ } from "./chunk-Z3ELZ77W.js";
4
+ import {
5
+ formatShortcut,
6
+ h,
7
+ uniqueId
8
+ } from "./chunk-HZRIBOPW.js";
9
+
10
+ // src/plugins/comments-panel.ts
11
+ var PALETTE = [
12
+ "#2563eb",
13
+ "#db2777",
14
+ "#16a34a",
15
+ "#ea580c",
16
+ "#7c3aed",
17
+ "#0891b2",
18
+ "#ca8a04",
19
+ "#dc2626"
20
+ ];
21
+ function colorFor(id) {
22
+ let hash = 0;
23
+ for (const ch of id) hash = hash * 31 + ch.charCodeAt(0) | 0;
24
+ return PALETTE[Math.abs(hash) % PALETTE.length];
25
+ }
26
+ function initials(name) {
27
+ const words = name.trim().split(/\s+/).filter(Boolean).slice(0, 2);
28
+ return words.map((word) => [...word][0].toUpperCase()).join("") || "?";
29
+ }
30
+ function createCommentsPanel(controller) {
31
+ const { editor, store, labels } = controller;
32
+ const lang = editor.options.language ?? "en";
33
+ const relative = new Intl.RelativeTimeFormat(lang, { numeric: "auto" });
34
+ const absolute = new Intl.DateTimeFormat(lang, { dateStyle: "medium", timeStyle: "short" });
35
+ const titleId = uniqueId("nova-comments-title");
36
+ const drafts = /* @__PURE__ */ new Map();
37
+ const draftMentions = /* @__PURE__ */ new Map();
38
+ let editing = null;
39
+ let showResolved = false;
40
+ const list = h("div", { className: "nova-comments-list" });
41
+ const countEl = h("span", { className: "nova-comments-count" });
42
+ const resolvedToggle = h("input", { type: "checkbox" });
43
+ resolvedToggle.addEventListener("change", () => {
44
+ showResolved = resolvedToggle.checked;
45
+ render();
46
+ });
47
+ const el = h(
48
+ "aside",
49
+ {
50
+ className: "nova-comments",
51
+ "aria-labelledby": titleId,
52
+ hidden: true,
53
+ onKeydown: ((event) => {
54
+ if (event.key !== "Escape") return;
55
+ event.stopPropagation();
56
+ if (controller.pending()) controller.cancelPending();
57
+ else controller.closePanel();
58
+ })
59
+ },
60
+ h(
61
+ "div",
62
+ { className: "nova-comments-head" },
63
+ h("h2", { id: titleId, className: "nova-comments-title" }, labels.panel),
64
+ countEl,
65
+ h(
66
+ "button",
67
+ {
68
+ type: "button",
69
+ className: "nova-btn nova-comments-close",
70
+ "aria-label": labels.close,
71
+ title: labels.close,
72
+ onClick: () => controller.closePanel()
73
+ },
74
+ "\xD7"
75
+ )
76
+ ),
77
+ h("label", { className: "nova-comments-filter" }, resolvedToggle, labels.showResolved),
78
+ list
79
+ );
80
+ function when(time) {
81
+ const seconds = Math.round((time - Date.now()) / 1e3);
82
+ const abs = Math.abs(seconds);
83
+ const text = abs < 45 ? relative.format(0, "second") : abs < 3600 ? relative.format(Math.round(seconds / 60), "minute") : abs < 86400 ? relative.format(Math.round(seconds / 3600), "hour") : abs < 86400 * 7 ? relative.format(Math.round(seconds / 86400), "day") : absolute.format(time);
84
+ return h(
85
+ "time",
86
+ { dateTime: new Date(time).toISOString(), title: absolute.format(time) },
87
+ text
88
+ );
89
+ }
90
+ function avatar(id, name) {
91
+ const span = h(
92
+ "span",
93
+ { className: "nova-comment-avatar", "aria-hidden": "true" },
94
+ initials(name)
95
+ );
96
+ span.style.backgroundColor = colorFor(id || name);
97
+ return span;
98
+ }
99
+ function composer(opts) {
100
+ const listId = uniqueId("nova-mention-list");
101
+ const textarea = h("textarea", {
102
+ className: "nova-input nova-comment-input",
103
+ rows: 2,
104
+ maxlength: COMMENT_MAX_LENGTH,
105
+ placeholder: opts.placeholder,
106
+ "aria-label": opts.placeholder,
107
+ "data-draft": opts.key
108
+ });
109
+ textarea.value = drafts.get(opts.key) ?? opts.initial ?? "";
110
+ const chosen = draftMentions.get(opts.key) ?? new Map((opts.initialMentions ?? []).map((m) => [m.id, m]));
111
+ draftMentions.set(opts.key, chosen);
112
+ const submitBtn = h(
113
+ "button",
114
+ { type: "button", className: "nova-button nova-button-primary" },
115
+ opts.submitLabel
116
+ );
117
+ const list2 = h("ul", {
118
+ id: listId,
119
+ className: "nova-mention-list",
120
+ role: "listbox",
121
+ "aria-label": labels.people,
122
+ hidden: true
123
+ });
124
+ let users = [];
125
+ let active = 0;
126
+ let query = null;
127
+ let request = 0;
128
+ if (controller.findUsers) {
129
+ textarea.setAttribute("role", "combobox");
130
+ textarea.setAttribute("aria-autocomplete", "list");
131
+ textarea.setAttribute("aria-controls", listId);
132
+ textarea.setAttribute("aria-expanded", "false");
133
+ }
134
+ const closeList = () => {
135
+ query = null;
136
+ users = [];
137
+ list2.hidden = true;
138
+ list2.replaceChildren();
139
+ textarea.setAttribute("aria-expanded", "false");
140
+ textarea.removeAttribute("aria-activedescendant");
141
+ };
142
+ const renderList = () => {
143
+ if (!query) return closeList();
144
+ list2.replaceChildren(
145
+ ...users.length ? users.map((user, index) => {
146
+ const option = h(
147
+ "li",
148
+ {
149
+ id: `${listId}-${index}`,
150
+ role: "option",
151
+ className: "nova-mention-option",
152
+ "aria-selected": String(index === active)
153
+ },
154
+ avatar(user.id, user.name),
155
+ h("span", { className: "nova-mention-name" }, user.name),
156
+ user.description ? h("span", { className: "nova-mention-detail" }, user.description) : null
157
+ );
158
+ option.addEventListener("mousedown", (event) => {
159
+ event.preventDefault();
160
+ pick(index);
161
+ });
162
+ return option;
163
+ }) : [h("li", { className: "nova-mention-empty", role: "presentation" }, labels.noPeople)]
164
+ );
165
+ list2.hidden = false;
166
+ textarea.setAttribute("aria-expanded", "true");
167
+ if (users.length) textarea.setAttribute("aria-activedescendant", `${listId}-${active}`);
168
+ else textarea.removeAttribute("aria-activedescendant");
169
+ };
170
+ const updateQuery = () => {
171
+ const findUsers = controller.findUsers;
172
+ if (!findUsers) return;
173
+ const caret = textarea.selectionStart ?? 0;
174
+ const before = textarea.value.slice(0, caret);
175
+ const match = /(?:^|\s)@([\p{L}\p{N}_.-]{0,30})$/u.exec(before);
176
+ if (!match) return closeList();
177
+ const text = match[1] ?? "";
178
+ query = { start: caret - text.length - 1, end: caret };
179
+ const id = ++request;
180
+ void findUsers(text).then((result) => {
181
+ if (id !== request || !query) return;
182
+ users = result;
183
+ active = 0;
184
+ renderList();
185
+ });
186
+ };
187
+ const pick = (index) => {
188
+ const user = users[index];
189
+ if (!user || !query) return;
190
+ const insert = `@${user.name} `;
191
+ textarea.value = textarea.value.slice(0, query.start) + insert + textarea.value.slice(query.end);
192
+ const caret = query.start + insert.length;
193
+ textarea.setSelectionRange(caret, caret);
194
+ chosen.set(user.id, { id: user.id, name: user.name });
195
+ closeList();
196
+ sync();
197
+ textarea.focus();
198
+ };
199
+ const sync = () => {
200
+ drafts.set(opts.key, textarea.value);
201
+ submitBtn.disabled = textarea.value.trim() === "";
202
+ };
203
+ const submit = () => {
204
+ const text = textarea.value;
205
+ if (!text.trim()) return;
206
+ drafts.delete(opts.key);
207
+ draftMentions.delete(opts.key);
208
+ opts.onSubmit(text, [...chosen.values()]);
209
+ };
210
+ textarea.addEventListener("input", () => {
211
+ sync();
212
+ updateQuery();
213
+ });
214
+ textarea.addEventListener("click", updateQuery);
215
+ textarea.addEventListener("blur", () => setTimeout(closeList, 0));
216
+ textarea.addEventListener("keydown", (event) => {
217
+ if (query && !list2.hidden) {
218
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
219
+ event.preventDefault();
220
+ if (!users.length) return;
221
+ active = (active + (event.key === "ArrowDown" ? 1 : -1) + users.length) % users.length;
222
+ renderList();
223
+ return;
224
+ }
225
+ if (event.key === "Enter" && !event.ctrlKey && !event.metaKey || event.key === "Tab") {
226
+ if (users.length) {
227
+ event.preventDefault();
228
+ pick(active);
229
+ return;
230
+ }
231
+ }
232
+ if (event.key === "Escape") {
233
+ event.preventDefault();
234
+ event.stopPropagation();
235
+ closeList();
236
+ return;
237
+ }
238
+ }
239
+ if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {
240
+ event.preventDefault();
241
+ submit();
242
+ }
243
+ });
244
+ submitBtn.addEventListener("click", submit);
245
+ sync();
246
+ const cancel = opts.onCancel ? h(
247
+ "button",
248
+ {
249
+ type: "button",
250
+ className: "nova-button",
251
+ onClick: () => {
252
+ drafts.delete(opts.key);
253
+ draftMentions.delete(opts.key);
254
+ opts.onCancel();
255
+ }
256
+ },
257
+ labels.cancel
258
+ ) : null;
259
+ return h(
260
+ "div",
261
+ { className: "nova-comment-composer" },
262
+ h("div", { className: "nova-mention-wrap" }, textarea, list2),
263
+ h("div", { className: "nova-comment-actions" }, cancel, submitBtn)
264
+ );
265
+ }
266
+ function commentText(comment) {
267
+ const p = h("p", { className: "nova-comment-text" });
268
+ const names = (comment.mentions ?? []).map((m) => `@${m.name}`).sort((a, b) => b.length - a.length);
269
+ if (!names.length) {
270
+ p.textContent = comment.text;
271
+ return p;
272
+ }
273
+ const escaped = names.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
274
+ const parts = comment.text.split(new RegExp(`(${escaped.join("|")})`, "g"));
275
+ p.append(
276
+ ...parts.map(
277
+ (part) => names.includes(part) ? h("span", { className: "nova-comment-mention" }, part) : part
278
+ )
279
+ );
280
+ return p;
281
+ }
282
+ function commentView(thread, comment, index) {
283
+ const mine = controller.canEdit(comment);
284
+ const isEditing = editing?.threadId === thread.id && editing.commentId === comment.id && mine;
285
+ const isSelf = comment.author.id === controller.author.id;
286
+ const head = h(
287
+ "div",
288
+ { className: "nova-comment-head" },
289
+ avatar(comment.author.id, comment.author.name),
290
+ h(
291
+ "span",
292
+ { className: "nova-comment-author" },
293
+ comment.author.name || labels.guest,
294
+ isSelf ? h("span", { className: "nova-comment-you" }, ` (${labels.you})`) : null
295
+ ),
296
+ when(comment.createdAt),
297
+ comment.editedAt ? h("span", { className: "nova-comment-edited" }, labels.edited) : null
298
+ );
299
+ const body = isEditing ? composer({
300
+ key: `edit:${thread.id}:${comment.id}`,
301
+ placeholder: labels.placeholder,
302
+ submitLabel: labels.save,
303
+ initial: comment.text,
304
+ initialMentions: comment.mentions ?? [],
305
+ onSubmit: (text) => {
306
+ editing = null;
307
+ store.editComment(thread.id, comment.id, text.trim());
308
+ },
309
+ onCancel: () => {
310
+ editing = null;
311
+ render();
312
+ }
313
+ }) : commentText(comment);
314
+ const actions = mine && !isEditing ? h(
315
+ "div",
316
+ { className: "nova-comment-tools" },
317
+ h(
318
+ "button",
319
+ {
320
+ type: "button",
321
+ className: "nova-link-btn",
322
+ onClick: () => {
323
+ editing = { threadId: thread.id, commentId: comment.id };
324
+ render();
325
+ focusDraft(`edit:${thread.id}:${comment.id}`);
326
+ }
327
+ },
328
+ labels.edit
329
+ ),
330
+ // Первый комментарий удаляется вместе с обсуждением.
331
+ index > 0 ? h(
332
+ "button",
333
+ {
334
+ type: "button",
335
+ className: "nova-link-btn",
336
+ onClick: () => store.deleteComment(thread.id, comment.id)
337
+ },
338
+ labels.remove
339
+ ) : null
340
+ ) : null;
341
+ return h("div", { className: "nova-comment-item" }, head, body, actions);
342
+ }
343
+ function threadView(thread) {
344
+ const active = controller.active() === thread.id;
345
+ const quote = controller.quote(thread.id);
346
+ const first = thread.comments[0];
347
+ const canDeleteThread = first ? controller.canEdit(first) : true;
348
+ const card = h(
349
+ "article",
350
+ {
351
+ className: [
352
+ "nova-thread",
353
+ active ? "is-active" : "",
354
+ thread.resolved ? "is-resolved" : "",
355
+ quote ? "" : "is-orphan"
356
+ ].filter(Boolean).join(" "),
357
+ "data-thread": thread.id,
358
+ tabindex: "-1",
359
+ "aria-current": active ? "true" : null
360
+ },
361
+ quote ? h("blockquote", { className: "nova-thread-quote" }, quote.slice(0, 140)) : h("p", { className: "nova-thread-orphan" }, labels.orphan),
362
+ thread.comments.map((comment, index) => commentView(thread, comment, index)),
363
+ thread.resolved ? h(
364
+ "p",
365
+ { className: "nova-thread-resolved" },
366
+ labels.resolvedBy.replace("{name}", thread.resolved.by.name || labels.guest)
367
+ ) : null,
368
+ active && !thread.resolved ? composer({
369
+ key: `reply:${thread.id}`,
370
+ placeholder: labels.replyPlaceholder,
371
+ submitLabel: labels.reply,
372
+ onSubmit: (text, mentions) => controller.reply(thread.id, text, mentions)
373
+ }) : null,
374
+ h(
375
+ "div",
376
+ { className: "nova-thread-tools" },
377
+ h(
378
+ "button",
379
+ {
380
+ type: "button",
381
+ className: "nova-button",
382
+ onClick: () => controller.setResolved(thread.id, !thread.resolved)
383
+ },
384
+ thread.resolved ? labels.reopen : labels.resolve
385
+ ),
386
+ canDeleteThread ? h(
387
+ "button",
388
+ {
389
+ type: "button",
390
+ className: "nova-button nova-button-danger",
391
+ onClick: () => controller.deleteThread(thread.id)
392
+ },
393
+ labels.deleteThread
394
+ ) : null
395
+ )
396
+ );
397
+ card.addEventListener("click", (event) => {
398
+ if (event.target.closest("button, textarea, input, a")) return;
399
+ if (controller.active() !== thread.id) controller.setActive(thread.id, true);
400
+ });
401
+ return card;
402
+ }
403
+ function focusDraft(key) {
404
+ const field = list.querySelector(`textarea[data-draft="${key}"]`);
405
+ if (!field) return;
406
+ field.focus();
407
+ field.setSelectionRange(field.value.length, field.value.length);
408
+ }
409
+ function render() {
410
+ const focused = list.contains(document.activeElement) ? document.activeElement.getAttribute("data-draft") : null;
411
+ const threads = [...store.threads()].sort(
412
+ (a, b) => controller.positionOf(a.id) - controller.positionOf(b.id) || a.createdAt - b.createdAt
413
+ );
414
+ const open = threads.filter((t) => !t.resolved);
415
+ const visible = showResolved ? threads : open;
416
+ countEl.textContent = open.length ? String(open.length) : "";
417
+ countEl.setAttribute("aria-label", labels.count.replace("{count}", String(open.length)));
418
+ const children = [];
419
+ if (controller.pending()) {
420
+ children.push(
421
+ h(
422
+ "article",
423
+ { className: "nova-thread is-active is-new" },
424
+ h(
425
+ "div",
426
+ { className: "nova-comment-head" },
427
+ avatar(controller.author.id, controller.author.name),
428
+ h("span", { className: "nova-comment-author" }, controller.author.name)
429
+ ),
430
+ composer({
431
+ key: "new",
432
+ placeholder: labels.placeholder,
433
+ submitLabel: labels.comment,
434
+ onSubmit: (text, mentions) => controller.submitPending(text, mentions),
435
+ onCancel: () => controller.cancelPending()
436
+ })
437
+ )
438
+ );
439
+ }
440
+ children.push(...visible.map(threadView));
441
+ if (children.length === 0) {
442
+ children.push(
443
+ h(
444
+ "p",
445
+ { className: "nova-comments-empty" },
446
+ labels.empty.replace("{shortcut}", formatShortcut(controller.shortcut))
447
+ )
448
+ );
449
+ }
450
+ list.replaceChildren(...children);
451
+ if (focused) focusDraft(focused);
452
+ list.querySelector(".nova-thread.is-active")?.scrollIntoView?.({ block: "nearest" });
453
+ }
454
+ return {
455
+ el,
456
+ render,
457
+ focusComposer: () => focusDraft("new"),
458
+ destroy: () => el.remove()
459
+ };
460
+ }
461
+ export {
462
+ createCommentsPanel
463
+ };
464
+ //# sourceMappingURL=comments-panel-FYJE3U64.js.map