@humanonlyweb/writer 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -2
  3. package/dist/components/WriterContent.d.ts +57 -0
  4. package/dist/components/WriterContent.js +114 -0
  5. package/dist/components/WriterEditor.js +232 -0
  6. package/dist/components/WriterEditor.vue.d.ts +70 -0
  7. package/dist/components/WriterToolbar.js +135 -0
  8. package/dist/components/WriterToolbar.vue.d.ts +27 -0
  9. package/dist/config.d.ts +39 -0
  10. package/dist/config.js +41 -0
  11. package/dist/docs/README.md +24 -0
  12. package/dist/docs/blocks.md +64 -0
  13. package/dist/docs/changelog.md +17 -0
  14. package/dist/docs/components/content.md +51 -0
  15. package/dist/docs/components/editor.md +236 -0
  16. package/dist/docs/components/toolbar.md +146 -0
  17. package/dist/docs/images.md +80 -0
  18. package/dist/docs/index.md +86 -0
  19. package/dist/docs/installation.md +74 -0
  20. package/dist/docs/limitations.md +11 -0
  21. package/dist/docs/localisation.md +35 -0
  22. package/dist/docs/parsing.md +47 -0
  23. package/dist/docs/security.md +16 -0
  24. package/dist/docs/storing.md +105 -0
  25. package/dist/docs/styling.md +47 -0
  26. package/dist/docs/word-count.md +16 -0
  27. package/dist/editor/commands.d.ts +1 -0
  28. package/dist/editor/commands.js +359 -0
  29. package/dist/editor/images.d.ts +1 -0
  30. package/dist/editor/images.js +400 -0
  31. package/dist/editor/live.d.ts +2 -0
  32. package/dist/editor/live.js +411 -0
  33. package/dist/editor/setup.d.ts +9 -0
  34. package/dist/editor/setup.js +485 -0
  35. package/dist/index.d.ts +11 -0
  36. package/dist/index.js +8 -0
  37. package/dist/load-parser.js +12 -0
  38. package/dist/nuxt/module.d.ts +35 -0
  39. package/dist/nuxt/module.js +114 -0
  40. package/dist/nuxt/runtime/plugin.d.ts +2 -0
  41. package/dist/nuxt/runtime/plugin.js +25 -0
  42. package/dist/nuxt/runtime/server/parse.d.ts +12 -0
  43. package/dist/nuxt/runtime/server/parse.js +15 -0
  44. package/dist/package.js +3 -0
  45. package/dist/parse.d.ts +16 -0
  46. package/dist/parse.js +62 -0
  47. package/dist/parser-options.d.ts +19 -0
  48. package/dist/placeholder.js +5 -0
  49. package/dist/render.d.ts +10 -0
  50. package/dist/render.js +97 -0
  51. package/dist/sanitize.d.ts +11 -0
  52. package/dist/sanitize.js +139 -0
  53. package/dist/stats.d.ts +8 -0
  54. package/dist/stats.js +17 -0
  55. package/dist/styles/core.css +275 -0
  56. package/dist/translations.d.ts +26 -0
  57. package/dist/translations.js +47 -0
  58. package/dist/types.d.ts +9 -0
  59. package/package.json +101 -4
@@ -0,0 +1,485 @@
1
+ import { activeCommands, commands, insertBlock, lineBreak, newParagraph } from "./commands.js";
2
+ import { uploadFiles } from "./images.js";
3
+ import { focused, livePreview } from "./live.js";
4
+ import { autocompletion, completionKeymap, snippet } from "@codemirror/autocomplete";
5
+ import { defaultKeymap, history, historyKeymap, redo, redoDepth, undo, undoDepth } from "@codemirror/commands";
6
+ import { markdownKeymap, markdownLanguage } from "@codemirror/lang-markdown";
7
+ import { HighlightStyle, Language, LanguageDescription, LanguageSupport, ParseContext, syntaxHighlighting, syntaxTree } from "@codemirror/language";
8
+ import { Compartment, EditorSelection, EditorState, Prec } from "@codemirror/state";
9
+ import { Decoration, EditorView, ViewPlugin, keymap, placeholder } from "@codemirror/view";
10
+ import { tags } from "@lezer/highlight";
11
+ import { MarkdownParser, parseCode } from "@lezer/markdown";
12
+ // src/editor/setup.ts
13
+ const highlightStyle = HighlightStyle.define([
14
+ {
15
+ tag: tags.strong,
16
+ class: "cm-md-strong"
17
+ },
18
+ {
19
+ tag: tags.emphasis,
20
+ class: "cm-md-em"
21
+ },
22
+ {
23
+ tag: tags.strikethrough,
24
+ class: "cm-md-strike"
25
+ },
26
+ {
27
+ tag: tags.monospace,
28
+ class: "cm-md-code"
29
+ },
30
+ {
31
+ tag: [tags.link, tags.url],
32
+ class: "cm-md-link"
33
+ },
34
+ {
35
+ tag: tags.quote,
36
+ class: "cm-md-quote"
37
+ },
38
+ {
39
+ tag: [
40
+ tags.processingInstruction,
41
+ tags.meta,
42
+ tags.contentSeparator
43
+ ],
44
+ class: "cm-md-mark"
45
+ },
46
+ {
47
+ tag: tags.comment,
48
+ class: "cm-md-comment"
49
+ }
50
+ ]);
51
+ const HEADING = /^(?:ATX|Setext)Heading([1-6])$/;
52
+ const codeLine = Decoration.line({ class: "cm-md-codeblock" });
53
+ /**
54
+ * Line classes for headings and code blocks, so their marks (`#`, fences) take the same
55
+ * size and font as their text. Visible lines only.
56
+ */
57
+ const blockLines = ViewPlugin.fromClass(class {
58
+ decorations;
59
+ constructor(view) {
60
+ this.decorations = this.build(view);
61
+ }
62
+ update(update) {
63
+ if (update.docChanged || update.viewportChanged || syntaxTree(update.state) !== syntaxTree(update.startState)) this.decorations = this.build(update.view);
64
+ }
65
+ build(view) {
66
+ const lines = [];
67
+ for (const { from, to } of view.visibleRanges) syntaxTree(view.state).iterate({
68
+ from,
69
+ to,
70
+ enter(node) {
71
+ const { doc } = view.state;
72
+ if (node.name === "FencedCode" || node.name === "CodeBlock") {
73
+ const last = doc.lineAt(node.to).number;
74
+ for (let n = doc.lineAt(node.from).number; n <= last; n++) lines.push(codeLine.range(doc.line(n).from));
75
+ return false;
76
+ }
77
+ const level = HEADING.exec(node.name)?.[1];
78
+ if (!level) return void 0;
79
+ const line = doc.lineAt(node.from);
80
+ lines.push(Decoration.line({ class: `cm-md-h${level}` }).range(line.from));
81
+ return false;
82
+ }
83
+ });
84
+ return Decoration.set(lines, true);
85
+ }
86
+ }, { decorations: (plugin) => plugin.decorations });
87
+ /**
88
+ * GFM Markdown, with Enter continuing lists and quotes. Not lang-markdown's `markdown()`:
89
+ * it always bundles HTML, CSS and JavaScript support (a third of the editor) for raw
90
+ * HTML, which Comark shows as text anyway.
91
+ */
92
+ function markdownSupport(codeLanguages) {
93
+ const base = markdownLanguage.parser;
94
+ const language = codeLanguages.length && base instanceof MarkdownParser ? new Language(markdownLanguage.data, base.configure(parseCode({ codeParser(info) {
95
+ const name = /\S*/.exec(info)?.[0] ?? "";
96
+ const found = LanguageDescription.matchLanguageName(codeLanguages, name, true);
97
+ if (!found) return null;
98
+ return found.support ? found.support.language.parser : ParseContext.getSkippingParser(found.load());
99
+ } })), [], "markdown") : markdownLanguage;
100
+ return new LanguageSupport(language, Prec.high(keymap.of(markdownKeymap)));
101
+ }
102
+ const theme = EditorView.theme({
103
+ "&": {
104
+ color: "inherit",
105
+ backgroundColor: "transparent",
106
+ font: "inherit"
107
+ },
108
+ "&.cm-focused": { outline: "none" },
109
+ ".cm-scroller": {
110
+ fontFamily: "inherit",
111
+ lineHeight: "inherit"
112
+ },
113
+ ".cm-content": {
114
+ caretColor: "currentColor",
115
+ padding: "0"
116
+ },
117
+ ".cm-line": { padding: "0" },
118
+ ".cm-line.cm-md-quote-line": {
119
+ paddingInlineStart: "var(--writer-quote-indent, 1em)",
120
+ boxShadow: "inset var(--writer-quote-border-width, 3px) 0 var(--writer-quote-border-color, color-mix(in srgb, currentColor 25%, transparent))"
121
+ },
122
+ ".cm-cursor, .cm-dropCursor": { borderLeftColor: "currentColor" },
123
+ ".cm-md-preview > [data-part='writer-content'] > :first-child, .cm-md-image figure": { marginBlockStart: "0 !important" },
124
+ ".cm-md-preview > [data-part='writer-content'] > :last-child, .cm-md-image figure": { marginBlockEnd: "0 !important" },
125
+ ".cm-line.cm-md-block-open": {
126
+ paddingInline: "var(--writer-block-inset, 0.75em)",
127
+ background: "var(--writer-block-background, color-mix(in srgb, currentColor 4%, transparent))"
128
+ }
129
+ });
130
+ const URL_PATTERN = /^https?:\/\/\S+$/;
131
+ /** Slash menu items that start a line rather than a block of their own. */
132
+ const LINE_STARTS = /* @__PURE__ */ new Set([
133
+ "heading1",
134
+ "heading2",
135
+ "heading3",
136
+ "bulletList",
137
+ "orderedList",
138
+ "taskList",
139
+ "quote"
140
+ ]);
141
+ const snapshot = (state) => ({
142
+ active: activeCommands(state),
143
+ undo: undoDepth(state) > 0,
144
+ redo: redoDepth(state) > 0
145
+ });
146
+ function createEditor(options) {
147
+ const readonly = new Compartment();
148
+ const live = new Compartment();
149
+ let liveOn = !!options.preview;
150
+ /**
151
+ * In live preview, an empty image card to drop or choose a file into (or type a URL);
152
+ * in source mode, the Markdown to fill in.
153
+ */
154
+ const imageCommand = (state) => liveOn ? insertBlock("![]()\n")(state) : insertBlock("![description](url)", 2)(state);
155
+ const attributes = new Compartment();
156
+ const blockNames = new Set(options.blocks.map((block) => block.name));
157
+ const { translations: t } = options;
158
+ function run(command) {
159
+ if (view.state.readOnly) return false;
160
+ const spec = command(view.state);
161
+ if (!spec) return false;
162
+ view.dispatch(view.state.update(spec, { scrollIntoView: true }));
163
+ return true;
164
+ }
165
+ let uploading = 0;
166
+ const uploadOptions = options.upload ? {
167
+ upload: options.upload,
168
+ onError: options.onUploadError,
169
+ onProgress: (change) => options.onUploading(uploading += change)
170
+ } : void 0;
171
+ /** Uploads files to the cursor (or `at`), each on its own line. */
172
+ function insertFiles(files, at = view.state.selection.main.head) {
173
+ if (!uploadOptions || view.state.readOnly || !files.length) return false;
174
+ uploadFiles(view, files, uploadOptions, { at });
175
+ return true;
176
+ }
177
+ const liveOptions = (render) => ({
178
+ render,
179
+ translations: t,
180
+ uploadInto: uploadOptions ? (target, file, range) => void uploadFiles(target, [file], uploadOptions, { replace: range }) : void 0
181
+ });
182
+ const slashItems = [
183
+ ...[
184
+ "heading1",
185
+ "heading2",
186
+ "heading3"
187
+ ].map((name, i) => ({
188
+ name,
189
+ label: t.commands[name],
190
+ snippet: `${"#".repeat(i + 1)} \${}`
191
+ })),
192
+ {
193
+ name: "bulletList",
194
+ label: t.commands.bulletList,
195
+ snippet: "- ${}"
196
+ },
197
+ {
198
+ name: "orderedList",
199
+ label: t.commands.orderedList,
200
+ snippet: "1. ${}"
201
+ },
202
+ {
203
+ name: "taskList",
204
+ label: t.commands.taskList,
205
+ snippet: "- [ ] ${}"
206
+ },
207
+ {
208
+ name: "quote",
209
+ label: t.commands.quote,
210
+ snippet: "> ${}"
211
+ },
212
+ {
213
+ name: "codeBlock",
214
+ label: t.commands.codeBlock,
215
+ snippet: "```${language}\n${}\n```"
216
+ },
217
+ {
218
+ name: "table",
219
+ label: t.commands.table,
220
+ snippet: "| ${Column} | ${Column} |\n| --- | --- |\n| ${} | |"
221
+ },
222
+ {
223
+ name: "divider",
224
+ label: t.commands.divider,
225
+ snippet: "---\n${}"
226
+ },
227
+ {
228
+ name: "image",
229
+ label: t.commands.image,
230
+ snippet: ""
231
+ },
232
+ {
233
+ name: "footnote",
234
+ label: t.commands.footnote,
235
+ snippet: ""
236
+ },
237
+ ...options.blocks
238
+ ];
239
+ /** `/` on an otherwise empty line lists blocks to insert. */
240
+ const slash = (context) => {
241
+ const line = context.state.doc.lineAt(context.pos);
242
+ const match = /^\s*\/([\w-]*)$/.exec(line.text.slice(0, context.pos - line.from));
243
+ if (!match || line.to !== context.pos) return null;
244
+ const query = match[1];
245
+ return {
246
+ from: context.pos - query.length,
247
+ options: slashItems.map((item) => ({
248
+ label: item.label,
249
+ detail: blockNames.has(item.name) ? `::${item.name}` : void 0,
250
+ type: "text",
251
+ apply: (view, completion, start, end) => {
252
+ const command = item.name === "footnote" ? commands.footnote : item.name === "image" ? imageCommand : void 0;
253
+ if (!command) {
254
+ const { doc } = view.state;
255
+ const here = doc.lineAt(start);
256
+ const filled = (n) => n >= 1 && n <= doc.lines && !!doc.line(n).text.trim();
257
+ const block = !LINE_STARTS.has(item.name);
258
+ const before = block && filled(here.number - 1) ? "\n" : "";
259
+ const after = block && filled(here.number + 1) ? "\n" : "";
260
+ return snippet(before + item.snippet + after)(view, completion, start - 1, end);
261
+ }
262
+ const removeSlash = view.state.update({ changes: {
263
+ from: start - 1,
264
+ to: end
265
+ } });
266
+ const added = removeSlash.state.update(command(removeSlash.state) ?? {});
267
+ view.dispatch({
268
+ changes: removeSlash.changes.compose(added.changes),
269
+ selection: added.selection,
270
+ scrollIntoView: true,
271
+ userEvent: "input.insert"
272
+ });
273
+ }
274
+ })),
275
+ validFor: /^[\w-]*$/
276
+ };
277
+ };
278
+ /** `](` followed by a query suggests the app's pages. */
279
+ const linkSource = async (context) => {
280
+ const match = context.matchBefore(/\]\([^)\s]*/);
281
+ if (!match || !options.links) return null;
282
+ const query = match.text.slice(2);
283
+ const suggestions = await options.links(query);
284
+ if (context.aborted || !suggestions.length) return null;
285
+ return {
286
+ from: match.from + 2,
287
+ filter: false,
288
+ options: suggestions.map((item) => ({
289
+ label: item.label,
290
+ detail: item.url,
291
+ type: "text",
292
+ apply: item.url
293
+ }))
294
+ };
295
+ };
296
+ const formatting = [
297
+ {
298
+ key: "Mod-b",
299
+ run: () => run(commands.bold)
300
+ },
301
+ {
302
+ key: "Mod-i",
303
+ run: () => run(commands.italic)
304
+ },
305
+ {
306
+ key: "Mod-k",
307
+ run: () => run(commands.link)
308
+ },
309
+ {
310
+ key: "Mod-e",
311
+ run: () => run(commands.code)
312
+ },
313
+ {
314
+ key: "Mod-Shift-x",
315
+ run: () => run(commands.strikethrough)
316
+ },
317
+ {
318
+ key: "Mod-Alt-1",
319
+ run: () => run(commands.heading1)
320
+ },
321
+ {
322
+ key: "Mod-Alt-2",
323
+ run: () => run(commands.heading2)
324
+ },
325
+ {
326
+ key: "Mod-Alt-3",
327
+ run: () => run(commands.heading3)
328
+ },
329
+ {
330
+ key: "Mod-Shift-7",
331
+ run: () => run(commands.orderedList)
332
+ },
333
+ {
334
+ key: "Mod-Shift-8",
335
+ run: () => run(commands.bulletList)
336
+ },
337
+ {
338
+ key: "Mod-Shift-9",
339
+ run: () => run(commands.taskList)
340
+ },
341
+ {
342
+ key: "Mod-Alt-f",
343
+ run: () => run(commands.footnote)
344
+ }
345
+ ];
346
+ let doc = options.doc;
347
+ const state = EditorState.create({
348
+ doc,
349
+ selection: options.selection ? EditorSelection.single(Math.min(options.selection.anchor, doc.length), Math.min(options.selection.head, doc.length)) : void 0,
350
+ extensions: [
351
+ history(),
352
+ Prec.high(keymap.of([{
353
+ key: "Enter",
354
+ run: () => run(newParagraph)
355
+ }, {
356
+ key: "Shift-Enter",
357
+ run: () => run(lineBreak)
358
+ }])),
359
+ markdownSupport(options.codeLanguages ?? []),
360
+ syntaxHighlighting(highlightStyle),
361
+ blockLines,
362
+ EditorView.lineWrapping,
363
+ EditorView.perLineTextDirection.of(true),
364
+ autocompletion({
365
+ override: [slash, linkSource],
366
+ icons: false
367
+ }),
368
+ readonly.of([EditorState.readOnly.of(options.readonly)]),
369
+ focused,
370
+ live.of(options.preview ? livePreview(liveOptions(options.preview)) : []),
371
+ options.placeholder ? placeholder(options.placeholder) : [],
372
+ attributes.of(EditorView.contentAttributes.of(options.attributes)),
373
+ keymap.of([
374
+ ...formatting,
375
+ ...completionKeymap,
376
+ ...historyKeymap,
377
+ ...defaultKeymap
378
+ ]),
379
+ EditorView.domEventHandlers({
380
+ paste(event, view) {
381
+ if (view.state.readOnly) return false;
382
+ const files = [...event.clipboardData?.files ?? []];
383
+ if (files.length && insertFiles(files)) {
384
+ event.preventDefault();
385
+ return true;
386
+ }
387
+ const text = event.clipboardData?.getData("text/plain").trim() ?? "";
388
+ if (!URL_PATTERN.test(text) || view.state.selection.ranges.some((r) => r.empty)) return false;
389
+ event.preventDefault();
390
+ view.dispatch({
391
+ ...view.state.changeByRange((range) => {
392
+ const insert = `[${view.state.sliceDoc(range.from, range.to)}](${text})`;
393
+ return {
394
+ changes: {
395
+ from: range.from,
396
+ to: range.to,
397
+ insert
398
+ },
399
+ range: EditorSelection.cursor(range.from + insert.length)
400
+ };
401
+ }),
402
+ userEvent: "input.paste"
403
+ });
404
+ return true;
405
+ },
406
+ drop(event, view) {
407
+ const files = [...event.dataTransfer?.files ?? []];
408
+ if (!files.length || !options.upload) return false;
409
+ const at = view.posAtCoords({
410
+ x: event.clientX,
411
+ y: event.clientY
412
+ });
413
+ event.preventDefault();
414
+ return insertFiles(files, at ?? void 0);
415
+ },
416
+ focus: () => options.onFocus(true),
417
+ blur: () => options.onFocus(false)
418
+ }),
419
+ EditorView.updateListener.of((update) => {
420
+ if (update.docChanged) {
421
+ doc = update.state.doc.toString();
422
+ options.onChange(doc);
423
+ }
424
+ if (update.docChanged || update.selectionSet || syntaxTree(update.state) !== syntaxTree(update.startState)) options.onState(snapshot(update.state));
425
+ }),
426
+ theme,
427
+ options.extensions ?? []
428
+ ]
429
+ });
430
+ const view = new EditorView({
431
+ state,
432
+ parent: options.parent
433
+ });
434
+ options.onState(snapshot(view.state));
435
+ return {
436
+ view,
437
+ run(name) {
438
+ if (name === "undo") return !view.state.readOnly && undo(view);
439
+ if (name === "redo") return !view.state.readOnly && redo(view);
440
+ return run(commands[name]);
441
+ },
442
+ insertFiles,
443
+ insert(text) {
444
+ if (view.state.readOnly) return;
445
+ view.dispatch(view.state.replaceSelection(text), {
446
+ scrollIntoView: true,
447
+ userEvent: "input"
448
+ });
449
+ },
450
+ /** The current Markdown, without serializing the document again. */
451
+ getDoc: () => doc,
452
+ /** Replaces only what differs, so the selection and undo history survive an outside change. */
453
+ setDoc(next) {
454
+ if (next === doc) return;
455
+ const current = doc;
456
+ let start = 0;
457
+ const max = Math.min(current.length, next.length);
458
+ while (start < max && current.charCodeAt(start) === next.charCodeAt(start)) start++;
459
+ let end = 0;
460
+ while (end < max - start && current.charCodeAt(current.length - 1 - end) === next.charCodeAt(next.length - 1 - end)) end++;
461
+ view.dispatch({
462
+ changes: {
463
+ from: start,
464
+ to: current.length - end,
465
+ insert: next.slice(start, next.length - end)
466
+ },
467
+ userEvent: "input.external"
468
+ });
469
+ },
470
+ /** Switches between live preview (with a renderer) and plain source. */
471
+ insertImage: () => run(imageCommand),
472
+ setPreview(render) {
473
+ liveOn = !!render;
474
+ view.dispatch({ effects: live.reconfigure(render ? livePreview(liveOptions(render)) : []) });
475
+ },
476
+ setReadonly(value) {
477
+ view.dispatch({ effects: readonly.reconfigure(EditorState.readOnly.of(value)) });
478
+ },
479
+ setAttributes(value) {
480
+ view.dispatch({ effects: attributes.reconfigure(EditorView.contentAttributes.of(value)) });
481
+ },
482
+ destroy: () => view.destroy()
483
+ };
484
+ }
485
+ export { createEditor };
@@ -0,0 +1,11 @@
1
+ import _default from "./components/WriterContent.js";
2
+ import { CommandName, WriterTranslations, WriterTranslationsInput, defaultTranslations } from "./translations.js";
3
+ import _default$1 from "./components/WriterEditor.vue.js";
4
+ import { ToolbarEditor } from "./types.js";
5
+ import _default$2 from "./components/WriterToolbar.vue.js";
6
+ import { ParserOptions } from "./parser-options.js";
7
+ import { countWords, readingMinutes } from "./stats.js";
8
+ import { MarkdownDocument } from "./parse.js";
9
+ import { WRITER_CONFIG_KEY, WriterBlock, WriterConfig, WriterOptions, createWriter, useTranslations, useWriterConfig } from "./config.js";
10
+ import { RenderOptions, renderDocument } from "./render.js";
11
+ export { type CommandName, type MarkdownDocument, type ParserOptions, type RenderOptions, type ToolbarEditor, WRITER_CONFIG_KEY, type WriterBlock, type WriterConfig, _default as WriterContent, _default$1 as WriterEditor, type WriterOptions, _default$2 as WriterToolbar, type WriterTranslations, type WriterTranslationsInput, countWords, createWriter, defaultTranslations, readingMinutes, renderDocument, useTranslations, useWriterConfig };
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ import { defaultTranslations } from "./translations.js";
2
+ import { WRITER_CONFIG_KEY, createWriter, useTranslations, useWriterConfig } from "./config.js";
3
+ import { renderDocument } from "./render.js";
4
+ import WriterContent_default from "./components/WriterContent.js";
5
+ import _sfc_main from "./components/WriterEditor.js";
6
+ import _sfc_main$1 from "./components/WriterToolbar.js";
7
+ import { countWords, readingMinutes } from "./stats.js";
8
+ export { WRITER_CONFIG_KEY, WriterContent_default as WriterContent, _sfc_main as WriterEditor, _sfc_main$1 as WriterToolbar, countWords, createWriter, defaultTranslations, readingMinutes, renderDocument, useTranslations, useWriterConfig };
@@ -0,0 +1,12 @@
1
+ // src/load-parser.ts
2
+ const parsers = /* @__PURE__ */ new WeakMap();
3
+ function loadParser(options) {
4
+ let parser = parsers.get(options);
5
+ if (!parser) {
6
+ parser = import("./parse.js").then(({ createParser }) => createParser(options));
7
+ parsers.set(options, parser);
8
+ parser.catch(() => parsers.delete(options));
9
+ }
10
+ return parser;
11
+ }
12
+ export { loadParser };
@@ -0,0 +1,35 @@
1
+ import { WriterTranslationsInput } from "../translations.js";
2
+ import { ParserOptions } from "../parser-options.js";
3
+ /** Auto-registered components. A test keeps it in step with `src/index.ts`. */
4
+ export declare const COMPONENTS: readonly ["WriterContent", "WriterEditor", "WriterToolbar"];
5
+ export interface ModuleOptions {
6
+ /**
7
+ * Folder inside each layer's `components/` whose components become blocks:
8
+ * `Callout.vue` → `::callout`, `media/Video.vue` → `::media-video`. `false` for none.
9
+ */
10
+ blocks: string | false;
11
+ /**
12
+ * Replace how native elements render, app-wide, by component name:
13
+ * `{ a: "NuxtLink", img: "NuxtImg" }`. Any component Nuxt registers works.
14
+ */
15
+ components: Record<string, string>;
16
+ /** Inject the core stylesheet. Turn off only to import it yourself, e.g. into a layer order. */
17
+ css: boolean;
18
+ /** Parser options for Markdown strings. Plugins aren't serializable: pre-parse on the server for those. */
19
+ parser: Omit<ParserOptions, "plugins">;
20
+ }
21
+ /** Labels and snippets for blocks, and the components' text, in `app.config.ts` under `writer`. */
22
+ export interface WriterAppConfig {
23
+ blocks?: Record<string, {
24
+ label?: string;
25
+ snippet?: string;
26
+ }>;
27
+ translations?: WriterTranslationsInput;
28
+ }
29
+ declare module "@nuxt/schema" {
30
+ interface AppConfigInput {
31
+ writer?: WriterAppConfig;
32
+ }
33
+ }
34
+ declare const _default: import("@nuxt/schema").NuxtModule<ModuleOptions, ModuleOptions, false>;
35
+ export { _default as default };
@@ -0,0 +1,114 @@
1
+ import { version } from "../package.js";
2
+ import { kebabCase } from "comark/utils";
3
+ import { createHash } from "node:crypto";
4
+ import { addComponent, addPlugin, addServerImports, addTemplate, addTypeTemplate, createResolver, defineNuxtModule, getLayerDirectories, resolveFiles, updateTemplates } from "@nuxt/kit";
5
+ // src/nuxt/module.ts
6
+ const PACKAGE = "@humanonlyweb/writer";
7
+ const TEMPLATE = "humanonlyweb-writer.mjs";
8
+ /** Auto-registered components. A test keeps it in step with `src/index.ts`. */
9
+ const COMPONENTS = [
10
+ "WriterContent",
11
+ "WriterEditor",
12
+ "WriterToolbar"
13
+ ];
14
+ var module_default = defineNuxtModule({
15
+ meta: {
16
+ name: PACKAGE,
17
+ version,
18
+ configKey: "writer",
19
+ compatibility: { nuxt: ">=4.0.0" }
20
+ },
21
+ defaults: {
22
+ blocks: "blocks",
23
+ components: {},
24
+ css: true,
25
+ parser: {}
26
+ },
27
+ setup(options, nuxt) {
28
+ const resolver = createResolver(import.meta.url);
29
+ const entry = resolver.resolve("../index");
30
+ nuxt.options.build.transpile.push("comark");
31
+ nuxt.options.build.transpile.push(resolver.resolve("./runtime"));
32
+ for (const name of COMPONENTS) addComponent({
33
+ name,
34
+ export: name,
35
+ filePath: entry
36
+ });
37
+ for (const [tag, name] of Object.entries(options.components)) if (!/^[A-Z_$][\w$]*$/i.test(name)) throw new Error(`[${PACKAGE}] components.${tag}: "${name}" isn't a component name.`);
38
+ if (options.css) nuxt.options.css.push(resolver.resolve("../styles/core.css"));
39
+ const folder = options.blocks;
40
+ const blockDirs = folder ? getLayerDirectories(nuxt).map((layer) => resolver.resolve(layer.app, "components", folder)) : [];
41
+ addTemplate({
42
+ filename: TEMPLATE,
43
+ write: false,
44
+ async getContents() {
45
+ const entries = [];
46
+ const seen = /* @__PURE__ */ new Set();
47
+ const files = await Promise.all(blockDirs.map((dir) => resolveFiles(dir, "**/*.vue")));
48
+ for (const [index, dir] of blockDirs.entries()) for (const file of files[index] ?? []) {
49
+ const name = kebabCase(file.slice(dir.length + 1).replace(/\.vue$/, "").replaceAll("/", "-"));
50
+ if (seen.has(name)) continue;
51
+ seen.add(name);
52
+ entries.push(` ${JSON.stringify(name)}: defineAsyncComponent(() => import(${JSON.stringify(file)})),`);
53
+ }
54
+ const elements = Object.entries(options.components);
55
+ return [
56
+ `import { defineAsyncComponent } from "vue";`,
57
+ ...elements.length ? [`import { ${[...new Set(elements.map(([, name]) => name))].join(", ")} } from "#components";`] : [],
58
+ `/** @type {Record<string, import("vue").Component>} */`,
59
+ `export const components = {${elements.map(([tag, name]) => ` ${JSON.stringify(tag)}: ${name},`).join("")} };`,
60
+ `/** @type {Record<string, import("vue").Component>} */`,
61
+ `export const blocks = {\n${entries.join("\n")}\n};`,
62
+ `/** @type {import("${PACKAGE}/parse").ParserOptions} */`,
63
+ `export const parser = ${JSON.stringify(options.parser)};`
64
+ ].join("\n");
65
+ }
66
+ });
67
+ nuxt.hook("builder:watch", async (event, path) => {
68
+ if (event !== "add" && event !== "unlink") return;
69
+ const file = resolver.resolve(nuxt.options.rootDir, path);
70
+ if (blockDirs.some((dir) => file.startsWith(`${dir}/`))) await updateTemplates({ filter: (template) => template.filename === TEMPLATE });
71
+ });
72
+ addPlugin(resolver.resolve("./runtime/plugin"));
73
+ nuxt.hook("nitro:config", (config) => {
74
+ config.virtual ??= {};
75
+ const hash = createHash("sha256").update(JSON.stringify(options.parser)).digest("hex");
76
+ const version$1 = `${version}+${hash.slice(0, 8)}`;
77
+ config.virtual["#humanonlyweb-writer/parser"] = [`export default ${JSON.stringify(options.parser)};`, `export const version = ${JSON.stringify(version$1)};`].join("\n");
78
+ });
79
+ addTypeTemplate({
80
+ filename: "types/humanonlyweb-writer-build.d.ts",
81
+ getContents: () => `declare module "#build/humanonlyweb-writer.mjs" {
82
+ export const blocks: Record<string, import("vue").Component>;
83
+ export const components: Record<string, import("vue").Component>;
84
+ export const parser: import("${PACKAGE}/parse").ParserOptions;
85
+ }`
86
+ });
87
+ addTypeTemplate({
88
+ filename: "types/humanonlyweb-writer.d.ts",
89
+ getContents: () => `declare module "#humanonlyweb-writer/parser" {
90
+ const options: Omit<import("${PACKAGE}/parse").ParserOptions, "plugins">;
91
+ export default options;
92
+ export const version: string;
93
+ }`
94
+ }, {
95
+ nitro: true,
96
+ nuxt: true
97
+ });
98
+ addServerImports([
99
+ {
100
+ name: "parseWriterDocument",
101
+ from: resolver.resolve("./runtime/server/parse")
102
+ },
103
+ {
104
+ name: "writerParserVersion",
105
+ from: resolver.resolve("./runtime/server/parse")
106
+ },
107
+ {
108
+ name: "countWords",
109
+ from: resolver.resolve("../stats")
110
+ }
111
+ ]);
112
+ }
113
+ });
114
+ export { COMPONENTS, module_default as default };
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
2
+ export { _default as default };