@humanonlyweb/writer 0.0.0-stage → 0.1.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/LICENSE +21 -0
  2. package/README.md +355 -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 +38 -0
  10. package/dist/config.js +41 -0
  11. package/dist/editor/commands.d.ts +1 -0
  12. package/dist/editor/commands.js +294 -0
  13. package/dist/editor/images.d.ts +1 -0
  14. package/dist/editor/images.js +388 -0
  15. package/dist/editor/live.d.ts +2 -0
  16. package/dist/editor/live.js +410 -0
  17. package/dist/editor/setup.d.ts +9 -0
  18. package/dist/editor/setup.js +466 -0
  19. package/dist/index.d.ts +10 -0
  20. package/dist/index.js +8 -0
  21. package/dist/load-parser.js +12 -0
  22. package/dist/nuxt/module.d.ts +38 -0
  23. package/dist/nuxt/module.js +92 -0
  24. package/dist/nuxt/runtime/plugin.d.ts +2 -0
  25. package/dist/nuxt/runtime/plugin.js +24 -0
  26. package/dist/nuxt/runtime/server/parse.d.ts +12 -0
  27. package/dist/nuxt/runtime/server/parse.js +15 -0
  28. package/dist/package.js +3 -0
  29. package/dist/parse.d.ts +31 -0
  30. package/dist/parse.js +62 -0
  31. package/dist/placeholder.js +5 -0
  32. package/dist/render.d.ts +10 -0
  33. package/dist/render.js +97 -0
  34. package/dist/sanitize.d.ts +11 -0
  35. package/dist/sanitize.js +139 -0
  36. package/dist/stats.d.ts +8 -0
  37. package/dist/stats.js +17 -0
  38. package/dist/styles/core.css +275 -0
  39. package/dist/translations.d.ts +26 -0
  40. package/dist/translations.js +47 -0
  41. package/dist/types.d.ts +9 -0
  42. package/docs/api.md +258 -0
  43. package/package.json +96 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 humanonlyweb
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,356 @@
1
- # Temporary Holding Version
1
+ # @humanonlyweb/writer
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
+ Markdown editor and renderer for Vue 3 and Nuxt 4. CodeMirror 6 for editing, [Comark](https://comark.dev) for parsing, blocks as your own Vue components. SSR-safe, unstyled apart from the editor's Markdown source.
4
+
5
+ Full API reference: [`docs/api.md`](docs/api.md), also shipped in the package.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ bun add @humanonlyweb/writer
11
+ ```
12
+
13
+ **Nuxt**
14
+
15
+ ```ts
16
+ export default defineNuxtConfig({
17
+ modules: ["@humanonlyweb/writer/nuxt"],
18
+ });
19
+ ```
20
+
21
+ | Option | Default | Description |
22
+ | ------------ | ---------- | ------------------------------------------------------------------------------------------------------- |
23
+ | `blocks` | `"blocks"` | Folder in each layer's `components/` whose components become blocks. `false`: none. |
24
+ | `components` | `{}` | Native elements to render with your components, app-wide, by name: `{ a: "NuxtLink", img: "NuxtImg" }`. |
25
+ | `css` | `true` | Inject `core.css`. |
26
+ | `parser` | `{}` | `footnotes`, `linkify`, `highlight`, `toc`. See [Parsing](#parsing). |
27
+
28
+ On the server, `parseWriterDocument(markdown)` (with these `parser` options), `writerParserVersion` and `countWords(markdown)` are auto-imported.
29
+
30
+ **Vue**
31
+
32
+ ```ts
33
+ import { createWriter } from "@humanonlyweb/writer";
34
+ import "@humanonlyweb/writer/core.css";
35
+
36
+ createApp(App)
37
+ .use(createWriter({ blocks: { callout: Callout }, components: { a: RouterLink } }))
38
+ .mount("#app");
39
+ ```
40
+
41
+ | Option | Description |
42
+ | -------------- | -------------------------------------------------------------------------------------------------------- |
43
+ | `blocks` | Components authors can use, by Markdown name, or `{ component, label, snippet }`. See [Blocks](#blocks). |
44
+ | `components` | Native elements to render with your components, e.g. `{ a: RouterLink, img: AppImage }`. |
45
+ | `parser` | [Parser options](#parsing) for Markdown parsed in the app. Use the same on the server. |
46
+ | `translations` | The built-in text; pass only what you change. A ref keeps it live. Keys: see `defaultTranslations`. |
47
+
48
+ ## Usage
49
+
50
+ ```vue
51
+ <script setup lang="ts">
52
+ const body = ref("");
53
+ const editor = useTemplateRef("editor");
54
+ </script>
55
+
56
+ <template>
57
+ <WriterToolbar :editor="editor" />
58
+ <WriterEditor ref="editor" v-model="body" label="Post body" name="body" />
59
+ <WriterContent :value="body" :debounce="100" />
60
+ </template>
61
+ ```
62
+
63
+ ### `<WriterEditor>`
64
+
65
+ Server-renders the content as it will read (a `<textarea>` in source mode); CodeMirror loads in the browser and takes over. Pages without an editor never load CodeMirror.
66
+
67
+ **Live preview** (the default): the document is always Markdown, but it reads like the published page.
68
+
69
+ - **Formatting:** marks hide except in the element being edited: `**bold**` shows its asterisks only while the cursor is in it, so the rest of the line doesn't move. Heading, quote and list marks show on the cursor's line. Bullets and task checkboxes render; clicking a checkbox toggles it.
70
+ - **Blocks** render with your components and content CSS. Clicking one, or arrowing into it, opens all of its source in a frame that keeps its place: set `--writer-block-inset` and `--writer-block-background` to your blocks' padding and background, and the text doesn't move when a block opens.
71
+ - **Images** on their own line are cards that never turn back into Markdown: the published figure, with the caption and alt text typed in place. Drop, paste or choose a file to fill or replace one; while it uploads, the card shows the local file at its real size and stores `width` and `height`, so neither the card nor the published page shifts. Arrowing onto a card selects it; Backspace or Delete removes it, Enter adds a paragraph after it.
72
+ - **Leaving the editor** shows everything as published: the open block closes, marks hide and cards deselect. The cursor stays put for when the author comes back. Switching windows doesn't count.
73
+
74
+ `mode="source"` shows plain Markdown throughout.
75
+
76
+ | Prop | Type | Description |
77
+ | --------------- | --------------------------------- | ---------------------------------------------------------------------------- |
78
+ | `v-model` | `string` | The Markdown. |
79
+ | `label` | `string` | Accessible name. Default: "Markdown editor". |
80
+ | `labelledby` | `string` | Id of the element naming it, instead of `label`. |
81
+ | `describedby` | `string` | Id of a hint or error. |
82
+ | `name` | `string` | Submits the Markdown with its form. |
83
+ | `placeholder` | `string` | |
84
+ | `readonly` | `boolean` | |
85
+ | `mode` | `"live" \| "source"` | Live preview (default) or plain Markdown. |
86
+ | `upload` | `(file: File) => Promise<string>` | Enables pasting, dropping and picking files. Resolve to the URL. |
87
+ | `links` | `(query) => { label, url }[]` | Suggests link targets after `](`, e.g. your pages. May return a promise. |
88
+ | `codeLanguages` | `LanguageDescription[]` | Fenced code highlighting, e.g. `languages` from `@codemirror/language-data`. |
89
+ | `extensions` | `Extension` | Extra CodeMirror extensions. Read once. |
90
+
91
+ Events: `focus`, `blur`, `upload-error (error, file)`.
92
+
93
+ Exposed: `ready`, `active` (formatting at the cursor), `canUpload`, `canUndo`, `canRedo`, `uploading`, `run(command)`, `insert(text)`, `insertFiles(files)`, `focus()`, `view()` (the `EditorView`).
94
+
95
+ **Uploads:** while a file uploads, the Markdown has an `#upload-…` placeholder where its URL will go, and `uploading` counts the uploads in progress. Wait for `uploading` to be 0 before saving; the URL arriving changes the Markdown, so a save on change runs again by itself. A placeholder saved anyway renders nothing, and in the editor becomes an empty card to fill again.
96
+
97
+ To load a different document, change the editor's `key`: an outside `v-model` change is applied as an edit, keeping undo history.
98
+
99
+ Keyboard (<kbd>Mod</kbd> is <kbd>Ctrl</kbd> or <kbd>⌘</kbd>):
100
+
101
+ | Keys | |
102
+ | ------------------------------- | ------------------------------------------------------------ |
103
+ | `Mod+B` `Mod+I` `Mod+E` `Mod+K` | Bold, italic, code, link |
104
+ | `Mod+Shift+X` | Strikethrough |
105
+ | `Mod+Alt+1` … `3` | Heading 1–3 |
106
+ | `Mod+Shift+7` `8` `9` | Numbered, bulleted, task list |
107
+ | `Mod+Alt+F` | Footnote |
108
+ | `Mod+Z` `Mod+Shift+Z` | Undo, redo |
109
+ | `Enter` | New paragraph (in a quote, inside it); in a list, a new item |
110
+ | `Shift+Enter` | Line break within the paragraph (`\` at the line end) |
111
+ | `/` on an empty line | Block menu |
112
+
113
+ <kbd>Tab</kbd> leaves the editor; indent lists with <kbd>Mod</kbd>+<kbd>]</kbd> / <kbd>[</kbd>. Pasting a URL over a selection links it.
114
+
115
+ ### `<WriterToolbar>`
116
+
117
+ `role="toolbar"`: one tab stop, arrow keys, Home and End. Buttons keep focus in the editor and show `aria-pressed`.
118
+
119
+ | Prop | Type | Description |
120
+ | -------- | --------------- | ----------------------------------------------------------------------------------------------------------- |
121
+ | `editor` | editor ref | The `<WriterEditor>` to format. |
122
+ | `items` | `CommandName[]` | Which commands, in order. Default: headings 2–3, bold, italic, link, code, quote, lists, code block, image. |
123
+ | `label` | `string` | Accessible name. Default: "Formatting". |
124
+
125
+ Commands: `bold`, `italic`, `strikethrough`, `code`, `link`, `heading1`–`heading3`, `quote`, `bulletList`, `orderedList`, `taskList`, `codeBlock`, `table`, `divider`, `image`, `footnote`, `undo`, `redo`. Headings, quotes and lists replace each other on a line. `image` opens the file picker when the editor has `upload`, and otherwise inserts an empty image card. `undo` and `redo` are `aria-disabled` when there's nothing to undo or redo.
126
+
127
+ Slot `item` (`{ command, label, active }`) replaces a button's content, e.g. with an icon; the label stays its accessible name. For a different toolbar entirely, call the editor's `run()` yourself.
128
+
129
+ ### `<WriterContent>`
130
+
131
+ | Prop | Type | Description |
132
+ | ------------ | ---------------------------- | -------------------------------------------------------------------------- |
133
+ | `value` | `string \| MarkdownDocument` | Markdown, or a document parsed ahead of time (no parser download). |
134
+ | `components` | `Record<string, Component>` | Native element overrides for this render, e.g. `{ a: NuxtLink }`. |
135
+ | `debounce` | `number` | Ms to wait before re-parsing changed Markdown. Use ~100 for live previews. |
136
+ | `tag` | `string` | Wrapper element. Default `div`. |
137
+
138
+ For your own wrapper, `renderDocument(document, { blocks, components })` returns the rendered Vue nodes.
139
+
140
+ ## Blocks
141
+
142
+ A block is a Vue component authors use in Markdown. Attributes become props, `#name` sections become slots:
143
+
144
+ ```md
145
+ ::callout{type="warning"}
146
+ #title
147
+ Heads up
148
+ #default
149
+ Body with **Markdown**.
150
+ ::
151
+ ```
152
+
153
+ In Nuxt, every component in `components/blocks/` is a block: `Callout.vue` → `::callout`, `media/Video.vue` → `::media-video`. They load on demand. Slash menu labels and snippets go in `app.config.ts`:
154
+
155
+ ```ts
156
+ export default defineAppConfig({
157
+ writer: {
158
+ blocks: {
159
+ callout: { label: "Callout", snippet: '::callout{type="${note}"}\n${}\n::' },
160
+ },
161
+ translations: { editor: "Éditeur" },
162
+ },
163
+ });
164
+ ```
165
+
166
+ Snippets use CodeMirror syntax: `${}` is the cursor, `${name}` a field Tab moves to.
167
+
168
+ Only registered blocks render. Any other component renders its content alone, so an unknown or removed block never breaks a page.
169
+
170
+ GitHub alerts (`> [!NOTE]`) render as a blockquote, or as your `note` block if you register one.
171
+
172
+ ## Images
173
+
174
+ Plain Markdown, no block needed: `![Alt text](/cat.png)`. Images load lazily. An image alone in its paragraph with a title becomes a figure:
175
+
176
+ ```md
177
+ ![A cat on a sofa](/cat.png "Our cat, 2026")
178
+ ```
179
+
180
+ ```html
181
+ <figure>
182
+ <img src="/cat.png" alt="A cat on a sofa" loading="lazy" decoding="async" />
183
+ <figcaption>Our cat, 2026</figcaption>
184
+ </figure>
185
+ ```
186
+
187
+ Size with attributes: `![Alt](/cat.png){width="800" height="600"}`; uploads add them for you. `data:image/…` URLs are allowed for images only. An image without a URL (`![]()`) isn't rendered; in the editor it's an empty card to fill. For responsive images or a CDN, replace `img` through `components` (e.g. `{ img: NuxtImg }`).
188
+
189
+ ## Word count
190
+
191
+ ```ts
192
+ import { countWords, readingMinutes } from "@humanonlyweb/writer";
193
+
194
+ const words = countWords(markdown);
195
+ readingMinutes(words); // at least 1, at 230 words a minute
196
+ ```
197
+
198
+ Counts what a reader sees: link text but not URLs, and no images, code, block fences, attributes, footnote labels or frontmatter. Chinese and Japanese count one word per character. Synchronous, fast enough for every keystroke, and the same on the server and in the browser, so it's safe to render during SSR.
199
+
200
+ ## Storing documents
201
+
202
+ Store the Markdown. It is the source of truth: portable, diffable, editable anywhere.
203
+
204
+ | Column | Type | |
205
+ | --------------------- | ---- | -------------------------------------------------------------- |
206
+ | `body` | text | What the editor produces. |
207
+ | `body_document` | json | Optional cache: the parsed document, for rendering. |
208
+ | `body_parser_version` | text | `writerParserVersion` when parsed: tells you when to re-parse. |
209
+
210
+ Parse on the server when saving, and render the cached document. Visitors then download neither the parser nor the editor:
211
+
212
+ ```ts
213
+ // server/api/posts/[id].put.ts (Nuxt: these are auto-imported)
214
+ await db.posts.update(id, {
215
+ body: input.body,
216
+ body_document: await parseWriterDocument(input.body),
217
+ body_parser_version: writerParserVersion,
218
+ word_count: countWords(input.body),
219
+ });
220
+ ```
221
+
222
+ Elsewhere, `import { createParser } from "@humanonlyweb/writer/parse"` with the options your app renders with.
223
+
224
+ ```vue
225
+ <WriterContent :value="post.document" />
226
+ ```
227
+
228
+ The cache is derived. `writerParserVersion` is this package's version plus a hash of the `parser` options; when a stored document's version differs, parse its `body` again (on read, or in a batch after deploying). Outside Nuxt, use the package version and your options the same way. Keep titles, slugs and dates in their own columns rather than frontmatter, so you can query them.
229
+
230
+ The playground is a worked example: a satire newsroom with drafts, published revisions, bylines and uploads, in SQLite.
231
+
232
+ ## Parsing
233
+
234
+ `@humanonlyweb/writer/parse` runs anywhere (no Vue, no DOM).
235
+
236
+ ```ts
237
+ import { createParser } from "@humanonlyweb/writer/parse";
238
+
239
+ const parse = createParser({ highlight: true, toc: true });
240
+ const document = await parse(markdown);
241
+ document.meta.toc; // { links: [{ id, text, depth, children }] }
242
+ ```
243
+
244
+ | Option | Default | Description |
245
+ | ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
246
+ | `footnotes` | `true` | `[^1]` footnotes. An object sets `label` and `backRef`. |
247
+ | `highlight` | `false` | Highlight fenced code with [rangi](https://comark.dev/plugins/built-in/rangi). An object sets `theme`, `lineNumbers`. Loaded only for documents with code. |
248
+ | `toc` | `false` | Table of contents in `meta.toc`. An object sets `depth`. |
249
+ | `linkify` | `true` | URL-like text becomes links. |
250
+ | `plugins` | `[]` | Other Comark plugins, e.g. `comark/plugins/shiki`. Not available in `nuxt.config`: parse on the server. |
251
+
252
+ Syntax: CommonMark, GFM (tables, task lists, strikethrough), frontmatter, footnotes, Comark components and `{.class #id}` attributes. Use the same options wherever you parse.
253
+
254
+ rangi colours code inline for the light theme and puts the dark theme in `--shiki-dark`. For dark mode:
255
+
256
+ ```css
257
+ @media (prefers-color-scheme: dark) {
258
+ .shiki span {
259
+ color: var(--shiki-dark) !important;
260
+ }
261
+ }
262
+ ```
263
+
264
+ ## Security
265
+
266
+ Content is treated as untrusted:
267
+
268
+ - Raw HTML is text.
269
+ - Only Markdown's own elements and registered blocks render; app-wide components can't be reached from Markdown.
270
+ - `script`, `style`, `iframe`, `object` and similar are removed; so are `on*` handlers, `style` attributes (except a highlighter's, inside code blocks) and URLs other than relative, `http(s)`, `mailto` and `tel`.
271
+ - `<WriterContent>` sanitizes documents again before rendering, so a stored document is safe even if it wasn't parsed by this package.
272
+
273
+ The same checks are exported from `@humanonlyweb/writer/parse`: `sanitize(nodes, isAllowed?)`, `isSafeUrl(url)` and `NATIVE_TAGS`.
274
+
275
+ Authors can still set `class` and `id` with `{…}` attributes. With untrusted authors and utility-class CSS (`fixed inset-0`), that's enough to restyle parts of the page: strip them from parsed documents, or render the elements through `components`, if that matters for your site.
276
+
277
+ Blocks receive attributes as authored. Validate any URL your block puts in an attribute other than `href` or `src`.
278
+
279
+ CodeMirror injects `<style>` elements. Under a strict CSP, pass `EditorView.cspNonce.of(nonce)` in `extensions`.
280
+
281
+ ## Styling
282
+
283
+ `core.css` is in `@layer humanonlyweb-writer`; your CSS wins. It styles the editor's Markdown source and gives the editor and rendered content one type scale, so a heading or code span is the same size in both. Change the scale with tokens, on any ancestor, and both follow:
284
+
285
+ ```css
286
+ :root {
287
+ --writer-h1: 2.5rem; /* through --writer-h6; defaults are the browser's */
288
+ --writer-heading-weight: 700;
289
+ --writer-code-font: "JetBrains Mono", monospace;
290
+ --writer-code-size: 0.875em;
291
+ --writer-quote-indent: 1em;
292
+ --writer-quote-border-width: 3px;
293
+ --writer-quote-border-color: #ddd;
294
+ --writer-block-inset: 1.25rem; /* an open block's padding */
295
+ --writer-block-background: #fbf6e3;
296
+ }
297
+ ```
298
+
299
+ If your prose CSS sets heading sizes directly, set these tokens to the same values, or the editor won't match. Hooks:
300
+
301
+ | Selector | |
302
+ | ---------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
303
+ | `[data-part="writer-editor"]` | Editor root. `[data-ready]` once loaded. |
304
+ | `[data-part="writer-fallback"]` | The content (or source-mode textarea) before load. |
305
+ | `[data-part="writer-host"] .cm-editor` | CodeMirror. |
306
+ | `.cm-md-preview`, `.cm-md-block-open`, `.cm-md-block-fence` | Rendered blocks (with `[data-part="writer-content"]` inside, so your content CSS applies), and blocks open for editing. |
307
+ | `[data-part="writer-image"]`, `.cm-md-image-frame`, `.cm-md-image-caption`, `.cm-md-image-alt` | Image cards. Their figure is inside `[data-part="writer-content"]`. |
308
+ | `.cm-md-bullet`, `.cm-md-task`, `.cm-md-quote-line`, `.cm-md-hr` | Live preview stand-ins for list, task, quote and rule syntax. |
309
+ | `.cm-md-h1`…`.cm-md-h6`, `.cm-md-codeblock`, `.cm-md-strong`, `.cm-md-em`, `.cm-md-code`, `.cm-md-link`, `.cm-md-mark` | Markdown source. |
310
+ | `[data-part="writer-toolbar"]`, `[data-part="writer-toolbar-item"][data-command]` | Toolbar. |
311
+ | `[data-part="writer-content"]` | Rendered content: style it as your site's prose. |
312
+
313
+ ## Limitations
314
+
315
+ - **Live preview** renders blocks and images on their own line. Tables, footnote references and inline images stay Markdown. A block still being typed (no closing `::`) stays Markdown until it's closed.
316
+ - **Blocks in the editor** render through the app, not the page: they get app-level plugins and `provide`s, but nothing provided by a parent component of `<WriterEditor>`.
317
+ - **Footnotes inside a block** are numbered within that block in the editor; the published page numbers them across the document.
318
+ - **An empty image card** is 16:9 until a file is chosen; the image's shape isn't known before then.
319
+ - **Indented content** (four spaces in, outside a block) stays Markdown in live preview: it's code, or deeply nested list content.
320
+ - **Chinese, Japanese and Korean input** (IME composition) hasn't been tested by hand yet; CodeMirror supports it, but the live preview's decorations haven't been checked against it.
321
+ - **Tested** in Chromium, Firefox and WebKit, automated. Touch devices and screen readers haven't been tested by hand yet.
322
+
323
+ ## For coding agents
324
+
325
+ The package ships its API reference at `node_modules/@humanonlyweb/writer/docs/api.md`, matching the installed version. To point agents at it, add to your project's `AGENTS.md` (or `CLAUDE.md`):
326
+
327
+ ```md
328
+ ## @humanonlyweb/writer
329
+
330
+ Before working with the editor, renderer or parser, read `node_modules/@humanonlyweb/writer/docs/api.md`. It matches the installed version; don't rely on memory.
331
+ ```
332
+
333
+ ## Development
334
+
335
+ ```bash
336
+ bun install
337
+ bunx playwright install chromium firefox webkit # once
338
+ bun run build # dist/
339
+ bun run test # Node (SSR, parser, commands) + browsers
340
+ bun run check # format, lint, types
341
+ bun run typecheck # vue-tsc
342
+ bun run playground # Nuxt app using the source
343
+ ```
344
+
345
+ The playground is a satire newsroom, in SQLite through Nitro's database layer (`playground/.data/db.sqlite`; schema in `playground/server/assets/database/schema.sql`):
346
+
347
+ - **Tables:** `sections`, `personas` (fictional bylines), `articles` (the working copy the editor autosaves), `revisions` (published versions, with `body_document` and `body_parser_version`), `assets` (uploads).
348
+ - `GET`/`PUT`/`DELETE /api/articles/[slug]`: the working copy; `DELETE` resets to the seed in `playground/server/assets/seed`. `POST /api/articles/[slug]/publish` parses it into a new revision. `GET /api/articles/[slug]/published` returns what readers see, re-parsing a revision stored by another parser version.
349
+ - `POST /api/uploads`: stores an image (PNG, JPEG, GIF, WebP or AVIF, checked by its bytes, up to 10 MB) and its `assets` row, and returns its URL, served from `/uploads/…`. This is the editor's `upload`.
350
+ - `/`: the editor, autosaving once uploads finish, with Publish. `/articles/[slug]`: the published page, rendered from the revision, marked up as a schema.org `SatiricalArticle`.
351
+
352
+ Release: bump `version`, push a `v*` tag. The workflow tests, publishes to npm (trusted publishing, no token) and creates a GitHub Release.
353
+
354
+ ## License
355
+
356
+ MIT
@@ -0,0 +1,57 @@
1
+ import { Component, PropType } from "vue";
2
+ import { MarkdownDocument } from "comark";
3
+ /**
4
+ * Renders Markdown, or a document parsed ahead of time with `@humanonlyweb/writer/parse`.
5
+ * Only native Markdown elements and registered blocks render.
6
+ */
7
+ declare const _default: import("vue").DefineComponent<import("vue").ExtractPropTypes<{
8
+ /** A Markdown string, or a parsed document (renders without loading the parser). */
9
+ value: {
10
+ type: PropType<string | MarkdownDocument>;
11
+ default: string;
12
+ };
13
+ /** Merged over the app's `components` for this render. */
14
+ components: {
15
+ type: PropType<Record<string, Component>>;
16
+ default: undefined;
17
+ };
18
+ /** Milliseconds to wait after the Markdown changes before parsing again. Use ~100 for live previews of long documents. */
19
+ debounce: {
20
+ type: NumberConstructor;
21
+ default: number;
22
+ };
23
+ /** The wrapping element. */
24
+ tag: {
25
+ type: StringConstructor;
26
+ default: string;
27
+ };
28
+ }>, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
29
+ [key: string]: any;
30
+ }>, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<import("vue").ExtractPropTypes<{
31
+ /** A Markdown string, or a parsed document (renders without loading the parser). */
32
+ value: {
33
+ type: PropType<string | MarkdownDocument>;
34
+ default: string;
35
+ };
36
+ /** Merged over the app's `components` for this render. */
37
+ components: {
38
+ type: PropType<Record<string, Component>>;
39
+ default: undefined;
40
+ };
41
+ /** Milliseconds to wait after the Markdown changes before parsing again. Use ~100 for live previews of long documents. */
42
+ debounce: {
43
+ type: NumberConstructor;
44
+ default: number;
45
+ };
46
+ /** The wrapping element. */
47
+ tag: {
48
+ type: StringConstructor;
49
+ default: string;
50
+ };
51
+ }>> & Readonly<{}>, {
52
+ components: Record<string, Component>;
53
+ value: string | MarkdownDocument<Record<string, any>, Record<string, any>>;
54
+ debounce: number;
55
+ tag: string;
56
+ }, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
57
+ export { _default as default };
@@ -0,0 +1,114 @@
1
+ import { useWriterConfig } from "../config.js";
2
+ import { loadParser } from "../load-parser.js";
3
+ import { renderDocument } from "../render.js";
4
+ import { isMarkdownDocument } from "comark/utils";
5
+ import { Suspense, computed, defineComponent, h, onScopeDispose, shallowRef, watch } from "vue";
6
+ // src/components/WriterContent.ts
7
+ const EMPTY = {
8
+ nodes: [],
9
+ frontmatter: {},
10
+ meta: {}
11
+ };
12
+ /**
13
+ * Parses `source`, then again whenever it changes: one parse at a time, always ending on
14
+ * the latest. Its default slot renders the document.
15
+ */
16
+ const ParsedContent = defineComponent({
17
+ name: "WriterParsedContent",
18
+ props: {
19
+ source: {
20
+ type: String,
21
+ required: true
22
+ },
23
+ parser: {
24
+ type: Object,
25
+ required: true
26
+ },
27
+ debounce: {
28
+ type: Number,
29
+ default: 0
30
+ }
31
+ },
32
+ async setup(props, { slots }) {
33
+ const document = shallowRef(EMPTY);
34
+ let running;
35
+ let queued = false;
36
+ async function parseLatest() {
37
+ queued = false;
38
+ try {
39
+ const parse = await loadParser(props.parser);
40
+ document.value = await parse(props.source);
41
+ } catch (error) {
42
+ console.error("[writer] couldn't parse Markdown:", error);
43
+ }
44
+ if (queued) return parseLatest();
45
+ }
46
+ function update() {
47
+ if (running) {
48
+ queued = true;
49
+ return running;
50
+ }
51
+ running = parseLatest().finally(() => running = void 0);
52
+ return running;
53
+ }
54
+ let timer;
55
+ watch(() => props.source, () => {
56
+ clearTimeout(timer);
57
+ if (props.debounce > 0) timer = setTimeout(update, props.debounce);
58
+ else update();
59
+ });
60
+ onScopeDispose(() => clearTimeout(timer));
61
+ await update();
62
+ return () => slots.default?.(document.value);
63
+ }
64
+ });
65
+ /**
66
+ * Renders Markdown, or a document parsed ahead of time with `@humanonlyweb/writer/parse`.
67
+ * Only native Markdown elements and registered blocks render.
68
+ */
69
+ var WriterContent_default = defineComponent({
70
+ name: "WriterContent",
71
+ props: {
72
+ /** A Markdown string, or a parsed document (renders without loading the parser). */
73
+ value: {
74
+ type: [String, Object],
75
+ default: ""
76
+ },
77
+ /** Merged over the app's `components` for this render. */
78
+ components: {
79
+ type: Object,
80
+ default: void 0
81
+ },
82
+ /** Milliseconds to wait after the Markdown changes before parsing again. Use ~100 for live previews of long documents. */
83
+ debounce: {
84
+ type: Number,
85
+ default: 0
86
+ },
87
+ /** The wrapping element. */
88
+ tag: {
89
+ type: String,
90
+ default: "div"
91
+ }
92
+ },
93
+ setup(props) {
94
+ const config = useWriterConfig();
95
+ const options = computed(() => ({
96
+ blocks: Object.fromEntries(Object.entries(config.blocks).map(([name, block]) => [name, block.component])),
97
+ components: {
98
+ ...config.components,
99
+ ...props.components
100
+ }
101
+ }));
102
+ const render = (document) => h(props.tag, { "data-part": "writer-content" }, renderDocument(document, options.value));
103
+ return () => {
104
+ const { value } = props;
105
+ if (isMarkdownDocument(value)) return render(value);
106
+ return h(Suspense, null, { default: () => h(ParsedContent, {
107
+ source: value,
108
+ parser: config.parser,
109
+ debounce: props.debounce
110
+ }, { default: render }) });
111
+ };
112
+ }
113
+ });
114
+ export { WriterContent_default as default };