@xenosystem/blocks 0.23.1 → 0.24.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.
@@ -0,0 +1,314 @@
1
+ import {
2
+ SAFE_IMAGE,
3
+ SAFE_LINK
4
+ } from "./chunk-MDNEMOZD.js";
5
+
6
+ // src/docs/document/extensions/Callout.ts
7
+ import { Node, mergeAttributes } from "@tiptap/core";
8
+ var Callout = Node.create({
9
+ name: "callout",
10
+ group: "block",
11
+ content: "block+",
12
+ defining: true,
13
+ addAttributes() {
14
+ return {
15
+ type: {
16
+ default: "info",
17
+ parseHTML: (element) => element.getAttribute("data-callout-type") || "info",
18
+ renderHTML: (attributes) => ({
19
+ "data-callout-type": attributes.type
20
+ })
21
+ }
22
+ };
23
+ },
24
+ parseHTML() {
25
+ return [
26
+ { tag: "div[data-callout-type]" },
27
+ { tag: "div.callout" }
28
+ ];
29
+ },
30
+ renderHTML({ HTMLAttributes }) {
31
+ const type = HTMLAttributes["data-callout-type"] || "info";
32
+ return [
33
+ "div",
34
+ mergeAttributes(HTMLAttributes, {
35
+ class: `callout ${type}`,
36
+ "data-callout-type": type
37
+ }),
38
+ 0
39
+ ];
40
+ },
41
+ addCommands() {
42
+ return {
43
+ setCallout: (attrs) => ({ commands }) => {
44
+ return commands.wrapIn(this.name, attrs);
45
+ },
46
+ toggleCallout: (attrs) => ({ commands }) => {
47
+ return commands.toggleWrap(this.name, attrs);
48
+ }
49
+ };
50
+ }
51
+ });
52
+
53
+ // src/docs/document/extensions/ToggleBlock.ts
54
+ import { Node as Node2, mergeAttributes as mergeAttributes2 } from "@tiptap/core";
55
+ var ToggleBlock = Node2.create({
56
+ name: "toggleBlock",
57
+ group: "block",
58
+ content: "block+",
59
+ defining: true,
60
+ addAttributes() {
61
+ return {
62
+ open: {
63
+ default: true,
64
+ parseHTML: (element) => element.getAttribute("data-open") !== "false",
65
+ renderHTML: (attributes) => ({
66
+ "data-open": String(attributes.open)
67
+ })
68
+ },
69
+ summary: {
70
+ default: "Toggle",
71
+ parseHTML: (element) => element.getAttribute("data-summary") || "Toggle",
72
+ renderHTML: (attributes) => ({
73
+ "data-summary": attributes.summary
74
+ })
75
+ }
76
+ };
77
+ },
78
+ parseHTML() {
79
+ return [
80
+ { tag: "div[data-toggle-block]" },
81
+ {
82
+ tag: "details",
83
+ getAttrs: (element) => ({
84
+ open: element.hasAttribute("open"),
85
+ summary: element.querySelector("summary")?.textContent || "Toggle"
86
+ })
87
+ }
88
+ ];
89
+ },
90
+ renderHTML({ HTMLAttributes }) {
91
+ return [
92
+ "details",
93
+ mergeAttributes2(HTMLAttributes, {
94
+ "data-toggle-block": "true",
95
+ ...HTMLAttributes["data-open"] === "true" ? { open: "open" } : {}
96
+ }),
97
+ ["summary", {}, HTMLAttributes["data-summary"] || "Toggle"],
98
+ ["div", { class: "toggle-content" }, 0]
99
+ ];
100
+ },
101
+ addCommands() {
102
+ return {
103
+ setToggleBlock: () => ({ commands }) => {
104
+ return commands.insertContent({
105
+ type: this.name,
106
+ attrs: { summary: "Click to expand", open: true },
107
+ content: [{ type: "paragraph", content: [{ type: "text", text: "Content here..." }] }]
108
+ });
109
+ }
110
+ };
111
+ }
112
+ });
113
+
114
+ // src/docs/document/extensions/PageBreak.ts
115
+ import { Node as Node3, mergeAttributes as mergeAttributes3 } from "@tiptap/core";
116
+ var PageBreak = Node3.create({
117
+ name: "pageBreak",
118
+ group: "block",
119
+ atom: true,
120
+ selectable: true,
121
+ draggable: false,
122
+ parseHTML() {
123
+ return [
124
+ { tag: "div[data-page-break]" },
125
+ {
126
+ tag: "div",
127
+ getAttrs: (element) => element.style.pageBreakAfter === "always" ? {} : false
128
+ }
129
+ ];
130
+ },
131
+ renderHTML({ HTMLAttributes }) {
132
+ return [
133
+ "div",
134
+ mergeAttributes3(HTMLAttributes, {
135
+ "data-page-break": "true",
136
+ class: "page-break",
137
+ contenteditable: "false",
138
+ style: "page-break-after: always;"
139
+ }),
140
+ ["div", { class: "page-break-rule" }],
141
+ ["span", { class: "page-break-label" }, "Page Break"],
142
+ ["div", { class: "page-break-rule" }]
143
+ ];
144
+ },
145
+ addCommands() {
146
+ return {
147
+ setPageBreak: () => ({ commands }) => {
148
+ return commands.insertContent({ type: this.name });
149
+ }
150
+ };
151
+ },
152
+ addKeyboardShortcuts() {
153
+ return {
154
+ "Mod-Enter": () => this.editor.commands.setPageBreak()
155
+ };
156
+ }
157
+ });
158
+
159
+ // src/docs/document/extensions/WikiLink.ts
160
+ import { Mark, mergeAttributes as mergeAttributes4 } from "@tiptap/core";
161
+ import { Plugin, PluginKey } from "@tiptap/pm/state";
162
+ var WikiLinkMark = Mark.create({
163
+ name: "wikiLink",
164
+ priority: 1e3,
165
+ addOptions() {
166
+ return {
167
+ onClickLink: () => {
168
+ },
169
+ HTMLAttributes: {
170
+ class: "wiki-link"
171
+ }
172
+ };
173
+ },
174
+ addAttributes() {
175
+ return {
176
+ pageId: {
177
+ default: null,
178
+ parseHTML: (element) => element.getAttribute("data-page-id"),
179
+ renderHTML: (attributes) => ({
180
+ "data-page-id": attributes.pageId
181
+ })
182
+ },
183
+ pageTitle: {
184
+ default: "",
185
+ parseHTML: (element) => element.getAttribute("data-page-title"),
186
+ renderHTML: (attributes) => ({
187
+ "data-page-title": attributes.pageTitle
188
+ })
189
+ }
190
+ };
191
+ },
192
+ parseHTML() {
193
+ return [
194
+ {
195
+ tag: "span[data-wiki-link]"
196
+ }
197
+ ];
198
+ },
199
+ renderHTML({ HTMLAttributes }) {
200
+ return [
201
+ "span",
202
+ mergeAttributes4(
203
+ this.options.HTMLAttributes,
204
+ HTMLAttributes,
205
+ { "data-wiki-link": "" }
206
+ ),
207
+ 0
208
+ ];
209
+ },
210
+ addCommands() {
211
+ return {
212
+ setWikiLink: (attrs) => ({ commands }) => {
213
+ return commands.setMark(this.name, attrs);
214
+ },
215
+ unsetWikiLink: () => ({ commands }) => {
216
+ return commands.unsetMark(this.name);
217
+ }
218
+ };
219
+ },
220
+ addProseMirrorPlugins() {
221
+ const { onClickLink } = this.options;
222
+ return [
223
+ new Plugin({
224
+ key: new PluginKey("wikiLinkClick"),
225
+ props: {
226
+ handleClick(view, pos) {
227
+ const { state } = view;
228
+ const $pos = state.doc.resolve(pos);
229
+ const marks = $pos.marks();
230
+ for (const mark of marks) {
231
+ if (mark.type.name === "wikiLink") {
232
+ const { pageId, pageTitle } = mark.attrs;
233
+ if (pageId || pageTitle) {
234
+ onClickLink(pageId || "", pageTitle || "");
235
+ return true;
236
+ }
237
+ }
238
+ }
239
+ return false;
240
+ }
241
+ }
242
+ })
243
+ ];
244
+ }
245
+ });
246
+
247
+ // src/docs/document/schema.ts
248
+ import StarterKit from "@tiptap/starter-kit";
249
+ import Underline from "@tiptap/extension-underline";
250
+ import TextAlign from "@tiptap/extension-text-align";
251
+ import Placeholder from "@tiptap/extension-placeholder";
252
+ import TaskList from "@tiptap/extension-task-list";
253
+ import TaskItem from "@tiptap/extension-task-item";
254
+ import Table from "@tiptap/extension-table";
255
+ import TableRow from "@tiptap/extension-table-row";
256
+ import TableCell from "@tiptap/extension-table-cell";
257
+ import TableHeader from "@tiptap/extension-table-header";
258
+ import Image from "@tiptap/extension-image";
259
+ import Link from "@tiptap/extension-link";
260
+ import Subscript from "@tiptap/extension-subscript";
261
+ import Superscript from "@tiptap/extension-superscript";
262
+ import Highlight from "@tiptap/extension-highlight";
263
+ import Typography from "@tiptap/extension-typography";
264
+ var SafeImage = Image.extend({
265
+ parseHTML() {
266
+ return [{ tag: "img[src]", getAttrs: (el) => SAFE_IMAGE.test(el.getAttribute("src") ?? "") ? null : false }];
267
+ }
268
+ });
269
+ function createDocumentExtensions(options = {}) {
270
+ const list = [
271
+ StarterKit.configure({
272
+ ...options.codeBlock ? { codeBlock: false } : {},
273
+ heading: { levels: [1, 2, 3, 4, 5, 6] },
274
+ ...options.history === false ? { history: false } : {}
275
+ }),
276
+ Underline,
277
+ TextAlign.configure({ types: ["heading", "paragraph"] }),
278
+ Placeholder.configure({ placeholder: options.placeholder ?? 'Start writing, or press "/" for commands...' }),
279
+ TaskList,
280
+ TaskItem.configure({ nested: true }),
281
+ Table.configure({ resizable: options.resizableTables ?? false }),
282
+ TableRow,
283
+ TableCell,
284
+ TableHeader,
285
+ SafeImage.configure({ inline: false }),
286
+ Link.configure({
287
+ openOnClick: false,
288
+ autolink: true,
289
+ HTMLAttributes: { rel: "noopener noreferrer nofollow", target: "_blank" },
290
+ // the format refuses anything else; the editor must not be able to produce what the format refuses
291
+ isAllowedUri: (url) => SAFE_LINK.test(String(url).trim())
292
+ }),
293
+ Subscript,
294
+ Superscript,
295
+ Highlight.configure({ multicolor: true }),
296
+ Typography,
297
+ Callout,
298
+ ToggleBlock,
299
+ PageBreak,
300
+ WikiLinkMark.configure({ onClickLink: options.onOpenPage ?? (() => {
301
+ }) })
302
+ ];
303
+ if (options.codeBlock) list.push(options.codeBlock);
304
+ return list;
305
+ }
306
+
307
+ export {
308
+ Callout,
309
+ ToggleBlock,
310
+ PageBreak,
311
+ WikiLinkMark,
312
+ SafeImage,
313
+ createDocumentExtensions
314
+ };
@@ -0,0 +1,259 @@
1
+ // src/docs/document/format.ts
2
+ var XDOC_FORMAT = "xeno.xdoc";
3
+ var XDOC_VERSION = 1;
4
+ var XDOC_EXTENSION = ".xdoc";
5
+ var DOCUMENT_NODE_TYPES = Object.freeze([
6
+ "doc",
7
+ "paragraph",
8
+ "text",
9
+ "heading",
10
+ "blockquote",
11
+ "bulletList",
12
+ "orderedList",
13
+ "listItem",
14
+ "taskList",
15
+ "taskItem",
16
+ "codeBlock",
17
+ "horizontalRule",
18
+ "hardBreak",
19
+ "table",
20
+ "tableRow",
21
+ "tableCell",
22
+ "tableHeader",
23
+ "image",
24
+ "callout",
25
+ "toggleBlock",
26
+ "pageBreak"
27
+ ]);
28
+ var DOCUMENT_MARK_TYPES = Object.freeze([
29
+ "bold",
30
+ "italic",
31
+ "strike",
32
+ "code",
33
+ "underline",
34
+ "link",
35
+ "subscript",
36
+ "superscript",
37
+ "highlight",
38
+ "wikiLink"
39
+ ]);
40
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
41
+ var SAFE_LINK = /^(https?:\/\/|mailto:)/i;
42
+ var SAFE_IMAGE = /^(https:\/\/|data:image\/(png|jpe?g|gif|webp);base64,)/i;
43
+ var CALLOUT_TYPES = /* @__PURE__ */ new Set(["info", "warning", "error", "success", "tip"]);
44
+ var ALIGN = /* @__PURE__ */ new Set(["left", "center", "right", "justify"]);
45
+ var COLOUR_VALUE = /^(#[0-9a-fA-F]{3,8}|[a-zA-Z]{3,20}|var\(--[a-zA-Z0-9-]{1,60}\))$/;
46
+ var LANGUAGE = /^[a-zA-Z0-9_+#.-]{0,40}$/;
47
+ var LIMITS = Object.freeze({ depth: 64, nodes: 5e4, text: 2e6 });
48
+ var isNull = (v) => v === null || v === void 0;
49
+ var optString = (max) => (v) => isNull(v) || typeof v === "string" && v.length <= max;
50
+ var align = (v) => isNull(v) || typeof v === "string" && ALIGN.has(v);
51
+ var int = (lo, hi) => (v) => isNull(v) || Number.isInteger(v) && v >= lo && v <= hi;
52
+ var bool = (v) => isNull(v) || typeof v === "boolean";
53
+ var colwidth = (v) => isNull(v) || Array.isArray(v) && v.length <= 64 && v.every((n) => Number.isInteger(n) && n >= 0 && n <= 1e4);
54
+ var dims = (v) => isNull(v) || typeof v === "number" && v >= 0 && v <= 1e5 || typeof v === "string" && /^\d{1,6}(px|%)?$/.test(v);
55
+ var NODE_ATTRS = {
56
+ paragraph: { textAlign: align },
57
+ heading: { level: int(1, 6), textAlign: align },
58
+ orderedList: { start: int(0, 1e6), type: optString(8) },
59
+ taskItem: { checked: bool },
60
+ codeBlock: { language: (v) => isNull(v) || typeof v === "string" && LANGUAGE.test(v) },
61
+ tableCell: { colspan: int(1, 1e3), rowspan: int(1, 1e3), colwidth },
62
+ tableHeader: { colspan: int(1, 1e3), rowspan: int(1, 1e3), colwidth },
63
+ image: { src: (v) => typeof v === "string" && v.length <= 8e6 && SAFE_IMAGE.test(v), alt: optString(1e3), title: optString(1e3), width: dims, height: dims },
64
+ callout: { type: (v) => isNull(v) || typeof v === "string" && CALLOUT_TYPES.has(v) },
65
+ toggleBlock: { open: bool, summary: optString(500) }
66
+ };
67
+ var MARK_ATTRS = {
68
+ link: {
69
+ href: (v) => typeof v === "string" && v.length <= 4e3 && SAFE_LINK.test(v.trim()),
70
+ target: (v) => isNull(v) || v === "_blank",
71
+ rel: optString(200),
72
+ class: (v) => isNull(v)
73
+ },
74
+ highlight: { color: (v) => isNull(v) || typeof v === "string" && COLOUR_VALUE.test(v) },
75
+ wikiLink: { pageId: (v) => isNull(v) || typeof v === "string" && (UUID.test(v) || /^[A-Za-z0-9_-]{1,128}$/.test(v)), pageTitle: optString(500) }
76
+ };
77
+ function validateContent(content, options = {}) {
78
+ const nodes = /* @__PURE__ */ new Set([...DOCUMENT_NODE_TYPES, ...options.extraNodes ?? []]);
79
+ const marks = /* @__PURE__ */ new Set([...DOCUMENT_MARK_TYPES, ...options.extraMarks ?? []]);
80
+ const extraN = new Set(options.extraNodes ?? []);
81
+ const extraM = new Set(options.extraMarks ?? []);
82
+ const problems = [];
83
+ let count = 0;
84
+ let text = 0;
85
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
86
+ const attrs = (where, kind, value, rules) => {
87
+ if (isNull(value)) return;
88
+ if (!isObj(value)) {
89
+ problems.push({ path: where, code: "bad_shape", detail: `${kind}.attrs is not an object` });
90
+ return;
91
+ }
92
+ for (const [k, v] of Object.entries(value)) {
93
+ const rule = rules?.[k];
94
+ if (!rule) {
95
+ if (!isNull(v)) problems.push({ path: where, code: "bad_attr", detail: `${kind} does not take "${k}"` });
96
+ continue;
97
+ }
98
+ if (!rule(v)) problems.push({ path: where, code: "bad_attr", detail: `${kind}.${k} is not allowed` });
99
+ }
100
+ };
101
+ const walk = (n, where, depth) => {
102
+ if (problems.length > 50) return;
103
+ if (depth > LIMITS.depth) {
104
+ problems.push({ path: where, code: "too_deep", detail: `deeper than ${LIMITS.depth}` });
105
+ return;
106
+ }
107
+ if (++count > LIMITS.nodes) {
108
+ if (count === LIMITS.nodes + 1) problems.push({ path: where, code: "too_large", detail: `more than ${LIMITS.nodes} nodes` });
109
+ return;
110
+ }
111
+ if (!isObj(n) || typeof n.type !== "string") {
112
+ problems.push({ path: where, code: "bad_shape", detail: "a node needs a string type" });
113
+ return;
114
+ }
115
+ if (!nodes.has(n.type)) {
116
+ problems.push({ path: where, code: "unknown_node", detail: n.type });
117
+ return;
118
+ }
119
+ if (!extraN.has(n.type)) attrs(where, n.type, n.attrs, NODE_ATTRS[n.type]);
120
+ if (n.type === "text") {
121
+ if (typeof n.text !== "string" || !n.text) problems.push({ path: where, code: "bad_shape", detail: "a text node needs text" });
122
+ else if ((text += n.text.length) > LIMITS.text) problems.push({ path: where, code: "too_large", detail: `more than ${LIMITS.text} characters` });
123
+ } else if (n.text !== void 0) problems.push({ path: where, code: "bad_shape", detail: `${n.type} cannot carry text` });
124
+ if (n.marks !== void 0) {
125
+ if (!Array.isArray(n.marks)) problems.push({ path: where, code: "bad_shape", detail: "marks is not a list" });
126
+ else n.marks.forEach((m, i) => {
127
+ if (!isObj(m) || typeof m.type !== "string") problems.push({ path: `${where}.marks[${i}]`, code: "bad_shape", detail: "a mark needs a string type" });
128
+ else if (!marks.has(m.type)) problems.push({ path: `${where}.marks[${i}]`, code: "unknown_mark", detail: m.type });
129
+ else if (!extraM.has(m.type)) attrs(`${where}.marks[${i}]`, m.type, m.attrs, MARK_ATTRS[m.type]);
130
+ });
131
+ }
132
+ if (n.content !== void 0) {
133
+ if (!Array.isArray(n.content)) problems.push({ path: where, code: "bad_shape", detail: "content is not a list" });
134
+ else n.content.forEach((c, i) => walk(c, `${where}.content[${i}]`, depth + 1));
135
+ }
136
+ };
137
+ if (!isObj(content) || content.type !== "doc") return [{ path: "content", code: "bad_shape", detail: "the root must be a doc node" }];
138
+ walk(content, "content", 0);
139
+ return problems;
140
+ }
141
+ var XdocError = class extends Error {
142
+ problems;
143
+ constructor(message, problems = []) {
144
+ super(message);
145
+ this.name = "XdocError";
146
+ this.problems = problems;
147
+ }
148
+ };
149
+ var emptyContent = () => ({ type: "doc", content: [{ type: "paragraph" }] });
150
+ function parseXdoc(input, options = {}) {
151
+ let raw = input;
152
+ if (typeof input === "string") {
153
+ try {
154
+ raw = JSON.parse(input);
155
+ } catch {
156
+ throw new XdocError("Not a XENO document: the file is not JSON");
157
+ }
158
+ }
159
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new XdocError("Not a XENO document");
160
+ const r = raw;
161
+ if (r.format !== void 0 && r.format !== XDOC_FORMAT) throw new XdocError(`Not a XENO document (format "${String(r.format)}")`);
162
+ if (r.version !== void 0 && (!Number.isInteger(r.version) || r.version > XDOC_VERSION)) {
163
+ throw new XdocError(`This document was written by a newer XENO Docs (version ${String(r.version)})`);
164
+ }
165
+ const problems = validateContent(r.content, options);
166
+ if (problems.length) throw new XdocError(`The document contains content this editor cannot show (${problems[0].detail})`, problems);
167
+ const now = Date.now();
168
+ const num = (v, d) => typeof v === "number" && Number.isFinite(v) ? v : d;
169
+ const content = r.content;
170
+ return {
171
+ format: XDOC_FORMAT,
172
+ version: XDOC_VERSION,
173
+ ...typeof r.id === "string" ? { id: r.id } : {},
174
+ title: typeof r.title === "string" ? r.title : "",
175
+ content,
176
+ created: num(r.created, now),
177
+ lastModified: num(r.lastModified, now),
178
+ wordCount: num(r.wordCount, wordCount(content)),
179
+ ...r.commentThreads && typeof r.commentThreads === "object" ? { commentThreads: r.commentThreads } : {}
180
+ };
181
+ }
182
+ function serializeXdoc(doc, options = {}) {
183
+ const problems = validateContent(doc.content, options);
184
+ if (problems.length) throw new XdocError(`The document contains content that cannot be saved (${problems[0].detail})`, problems);
185
+ const file = {
186
+ format: XDOC_FORMAT,
187
+ version: XDOC_VERSION,
188
+ ...doc.id ? { id: doc.id } : {},
189
+ title: doc.title,
190
+ content: doc.content,
191
+ created: doc.created,
192
+ lastModified: doc.lastModified,
193
+ wordCount: doc.wordCount ?? wordCount(doc.content),
194
+ ...doc.commentThreads && typeof doc.commentThreads === "object" ? { commentThreads: doc.commentThreads } : {}
195
+ };
196
+ return JSON.stringify(file, null, options.pretty === false ? void 0 : 2);
197
+ }
198
+ var BLOCKS = /* @__PURE__ */ new Set(["paragraph", "heading", "blockquote", "listItem", "taskItem", "codeBlock", "tableCell", "tableHeader", "callout", "toggleBlock"]);
199
+ function plainText(content) {
200
+ const out = [];
201
+ const walk = (n) => {
202
+ if (!n) return;
203
+ if (n.type === "text" && typeof n.text === "string") out.push(n.text);
204
+ else if (n.type === "hardBreak") out.push(" ");
205
+ if (n.type === "toggleBlock" && typeof n.attrs?.summary === "string") out.push(` ${n.attrs.summary} `);
206
+ for (const c of n.content ?? []) walk(c);
207
+ if (BLOCKS.has(n.type)) out.push(" ");
208
+ };
209
+ walk(content);
210
+ return out.join("").replace(/\s+/g, " ").trim();
211
+ }
212
+ function wordCount(content) {
213
+ const t = plainText(content);
214
+ return t ? t.split(" ").length : 0;
215
+ }
216
+ function pageLinksIn(content) {
217
+ const seen = /* @__PURE__ */ new Set();
218
+ const walk = (n) => {
219
+ if (!n) return;
220
+ for (const m of n.marks ?? []) {
221
+ const id = m.type === "wikiLink" ? m.attrs?.pageId : null;
222
+ if (typeof id === "string" && id) seen.add(id.toLowerCase());
223
+ }
224
+ for (const c of n.content ?? []) walk(c);
225
+ };
226
+ walk(content);
227
+ return [...seen];
228
+ }
229
+ function nodeTypesIn(content) {
230
+ const seen = /* @__PURE__ */ new Set();
231
+ const walk = (n) => {
232
+ if (!n) return;
233
+ seen.add(n.type);
234
+ for (const m of n.marks ?? []) seen.add(`mark:${m.type}`);
235
+ for (const c of n.content ?? []) walk(c);
236
+ };
237
+ walk(content);
238
+ return seen;
239
+ }
240
+
241
+ export {
242
+ XDOC_FORMAT,
243
+ XDOC_VERSION,
244
+ XDOC_EXTENSION,
245
+ DOCUMENT_NODE_TYPES,
246
+ DOCUMENT_MARK_TYPES,
247
+ SAFE_LINK,
248
+ SAFE_IMAGE,
249
+ LIMITS,
250
+ validateContent,
251
+ XdocError,
252
+ emptyContent,
253
+ parseXdoc,
254
+ serializeXdoc,
255
+ plainText,
256
+ wordCount,
257
+ pageLinksIn,
258
+ nodeTypesIn
259
+ };
@@ -0,0 +1,60 @@
1
+ import { AnyExtension } from '@tiptap/core';
2
+ import * as Y from 'yjs';
3
+ import { Awareness } from 'y-protocols/awareness';
4
+ import { X as XenoDocNode } from '../format-BoLLqtrs.js';
5
+
6
+ /**
7
+ * Live co-editing for the document block — `@xenosystem/blocks/docs/collaboration`.
8
+ *
9
+ * The same construction XENO Docs uses (its DocumentEditor): TipTap's `Collaboration` extension binds the editor to an
10
+ * XML fragment of a Y.js document (field `prosemirror`), and `CollaborationCursor` draws the other writers' carets from
11
+ * a y-protocols `Awareness`. Edits from everyone merge as a CRDT, so two people typing in the same paragraph both land
12
+ * and every mark, block and attribute of the shared schema travels intact (nothing goes through Markdown).
13
+ *
14
+ * The block never connects anything. The HOST owns the transport (XENO Multiplayer, a provider) and the saving: it
15
+ * hands this module the `Y.Doc` and an `Awareness` it keeps in step, mounts the surface with
16
+ * `{ shared: true, history: false, extensions: createCollaborationExtensions(...) }`, and decides who seeds the shared
17
+ * document from the saved file ({@link seedSharedDocument}) and who writes it back to storage. This lives in its own
18
+ * subpath so a consumer that never co-edits does not need Y.js.
19
+ *
20
+ * @module
21
+ */
22
+
23
+ /** XENO Docs' field name: a document co-edited here and in XENO Docs is the same fragment. */
24
+ declare const SHARED_FIELD = "prosemirror";
25
+ interface CollaborationOptions {
26
+ /** The shared document. Its XML fragment `field` IS the document's content while it is open. */
27
+ document: Y.Doc;
28
+ /** Fragment name. Default {@link SHARED_FIELD}. */
29
+ field?: string;
30
+ /**
31
+ * Other writers' carets and selections: an Awareness the host keeps in step with its transport, and how THIS writer
32
+ * appears to them. The colour is the host's (a theme token's value), never the block's.
33
+ */
34
+ cursors?: {
35
+ awareness: Awareness;
36
+ user: {
37
+ name: string;
38
+ color: string;
39
+ };
40
+ };
41
+ }
42
+ /** The extensions that bind a document surface to a shared document. Mount with `shared: true, history: false`. */
43
+ declare function createCollaborationExtensions(options: CollaborationOptions): AnyExtension[];
44
+ /** True when the shared document holds nothing yet. */
45
+ declare function isSharedDocumentEmpty(document: Y.Doc, field?: string): boolean;
46
+ /**
47
+ * Put a saved document into an EMPTY shared one (the first writer to open it). Does nothing, and returns false, when it
48
+ * already holds content: one seed only, so two writers opening at once never get the text twice — the host still
49
+ * decides which one seeds. Content the schema cannot represent throws, so nothing is silently dropped.
50
+ */
51
+ declare function seedSharedDocument(document: Y.Doc, content: XenoDocNode, field?: string): boolean;
52
+ /**
53
+ * Replace the shared document with a saved one, in one change (a newer version was saved somewhere nobody here was
54
+ * writing, and nobody is in it now). Everyone still connected receives the replacement as an ordinary edit.
55
+ */
56
+ declare function replaceSharedDocument(document: Y.Doc, content: XenoDocNode, field?: string): void;
57
+ /** The shared document as the block's JSON, for a host that saves without an editor mounted. */
58
+ declare function sharedDocumentContent(document: Y.Doc, field?: string): XenoDocNode;
59
+
60
+ export { type CollaborationOptions, SHARED_FIELD, createCollaborationExtensions, isSharedDocumentEmpty, replaceSharedDocument, seedSharedDocument, sharedDocumentContent };
@@ -0,0 +1,49 @@
1
+ import {
2
+ createDocumentExtensions
3
+ } from "../chunk-KC2QBI2I.js";
4
+ import "../chunk-MDNEMOZD.js";
5
+ import "../chunk-2KG3PWR4.js";
6
+
7
+ // src/docs/collaboration.ts
8
+ import { getSchema } from "@tiptap/core";
9
+ import Collaboration from "@tiptap/extension-collaboration";
10
+ import CollaborationCursor from "@tiptap/extension-collaboration-cursor";
11
+ import { prosemirrorJSONToYXmlFragment, yXmlFragmentToProseMirrorRootNode } from "y-prosemirror";
12
+ var SHARED_FIELD = "prosemirror";
13
+ function createCollaborationExtensions(options) {
14
+ const field = options.field ?? SHARED_FIELD;
15
+ const list = [Collaboration.configure({ document: options.document, field })];
16
+ if (options.cursors) list.push(CollaborationCursor.configure({ provider: { awareness: options.cursors.awareness }, user: options.cursors.user }));
17
+ return list;
18
+ }
19
+ var schema = null;
20
+ function documentSchema() {
21
+ return schema ??= getSchema(createDocumentExtensions({ history: false }));
22
+ }
23
+ var fragmentOf = (document, field) => document.getXmlFragment(field ?? SHARED_FIELD);
24
+ function isSharedDocumentEmpty(document, field) {
25
+ return fragmentOf(document, field).length === 0;
26
+ }
27
+ function seedSharedDocument(document, content, field) {
28
+ if (!isSharedDocumentEmpty(document, field)) return false;
29
+ document.transact(() => {
30
+ prosemirrorJSONToYXmlFragment(documentSchema(), content, fragmentOf(document, field));
31
+ });
32
+ return true;
33
+ }
34
+ function replaceSharedDocument(document, content, field) {
35
+ document.transact(() => {
36
+ prosemirrorJSONToYXmlFragment(documentSchema(), content, fragmentOf(document, field));
37
+ });
38
+ }
39
+ function sharedDocumentContent(document, field) {
40
+ return yXmlFragmentToProseMirrorRootNode(fragmentOf(document, field), documentSchema()).toJSON();
41
+ }
42
+ export {
43
+ SHARED_FIELD,
44
+ createCollaborationExtensions,
45
+ isSharedDocumentEmpty,
46
+ replaceSharedDocument,
47
+ seedSharedDocument,
48
+ sharedDocumentContent
49
+ };