@humanonlyweb/writer 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @humanonlyweb/writer
2
2
 
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.
3
+ A Markdown editor and renderer for Vue 3 and Nuxt. You write Markdown; it reads like the published page. Blocks are your own Vue components. SSR-safe, accessible, unstyled.
4
4
 
5
- Full API reference: [`docs/api.md`](docs/api.md), also shipped in the package.
5
+ **Docs:** [writer.humanonlyweb.com](https://writer.humanonlyweb.com) · for AI agents: [llms.txt](https://writer.humanonlyweb.com/llms.txt), or the same docs in the package, at `node_modules/@humanonlyweb/writer/dist/docs`
6
6
 
7
7
  ## Install
8
8
 
@@ -18,34 +18,16 @@ export default defineNuxtConfig({
18
18
  });
19
19
  ```
20
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
21
  **Vue**
31
22
 
32
23
  ```ts
33
24
  import { createWriter } from "@humanonlyweb/writer";
34
25
  import "@humanonlyweb/writer/core.css";
35
26
 
36
- createApp(App)
37
- .use(createWriter({ blocks: { callout: Callout }, components: { a: RouterLink } }))
38
- .mount("#app");
27
+ createApp(App).use(createWriter()).mount("#app");
39
28
  ```
40
29
 
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
30
+ ## Use
49
31
 
50
32
  ```vue
51
33
  <script setup lang="ts">
@@ -55,301 +37,26 @@ const editor = useTemplateRef("editor");
55
37
 
56
38
  <template>
57
39
  <WriterToolbar :editor="editor" />
58
- <WriterEditor ref="editor" v-model="body" label="Post body" name="body" />
59
- <WriterContent :value="body" :debounce="100" />
40
+ <WriterEditor ref="editor" v-model="body" label="Post body" />
41
+ <WriterContent :value="body" />
60
42
  </template>
61
43
  ```
62
44
 
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
- ```
45
+ Store the Markdown, parse it on save, and render the parsed document: see [Storing documents](https://writer.humanonlyweb.com/storing).
332
46
 
333
47
  ## Development
334
48
 
335
49
  ```bash
336
50
  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
51
+ bunx playwright install chromium firefox webkit # once, for the browser tests
52
+ bun run build # library, then the docs as Markdown → dist/
53
+ bun run test # Node (SSR, parser, commands) + browsers
54
+ bun run check # format, lint, types
55
+ bun run typecheck # vue-tsc
56
+ bun run docs # docs site, from source
343
57
  ```
344
58
 
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.
59
+ Release: bump `version` and push a `v*` tag. CI tests, publishes to npm and creates a GitHub Release.
353
60
 
354
61
  ## License
355
62
 
@@ -1,7 +1,7 @@
1
1
  import { useTranslations, useWriterConfig } from "../config.js";
2
2
  import { loadParser } from "../load-parser.js";
3
3
  import WriterContent_default from "./WriterContent.js";
4
- import { computed, createCommentVNode, createElementBlock, createElementVNode, createVNode, defineComponent, getCurrentInstance, h, mergeModels, nextTick, onBeforeUnmount, onMounted, openBlock, render, shallowRef, unref, useModel, useTemplateRef, watch } from "vue";
4
+ import { computed, createCommentVNode, createElementBlock, createElementVNode, createVNode, defineComponent, getCurrentInstance, h, mergeModels, nextTick, onBeforeUnmount, onMounted, openBlock, render, renderSlot, shallowRef, unref, useModel, useSlots, useTemplateRef, watch } from "vue";
5
5
  // src/components/WriterEditor.vue
6
6
  const _hoisted_1 = [
7
7
  "data-mode",
@@ -23,7 +23,9 @@ const _hoisted_3 = [
23
23
  "readonly"
24
24
  ];
25
25
  const _hoisted_4 = ["hidden"];
26
- const _hoisted_5 = ["name", "value"];
26
+ const _hoisted_5 = { "data-slot": "replace" };
27
+ const _hoisted_6 = { "data-slot": "remove" };
28
+ const _hoisted_7 = ["name", "value"];
27
29
  const _sfc_main = /*@__PURE__*/ defineComponent({
28
30
  __name: "WriterEditor",
29
31
  props: /*@__PURE__*/ mergeModels({
@@ -50,6 +52,7 @@ const _sfc_main = /*@__PURE__*/ defineComponent({
50
52
  setup(__props, { expose: __expose, emit: __emit }) {
51
53
  const model = useModel(__props, "modelValue");
52
54
  const props = __props;
55
+ const slots = useSlots();
53
56
  const emit = __emit;
54
57
  const t = useTranslations();
55
58
  const config = useWriterConfig();
@@ -71,6 +74,12 @@ const _sfc_main = /*@__PURE__*/ defineComponent({
71
74
  const fallback = useTemplateRef("fallback");
72
75
  const host = useTemplateRef("host");
73
76
  const picker = useTemplateRef("picker");
77
+ const iconSource = useTemplateRef("iconSource");
78
+ const slotIcon = (name) => slots[`image-${name}`] ? () => {
79
+ const copy = document.createDocumentFragment();
80
+ for (const node of iconSource.value?.querySelector(`[data-slot="${name}"]`)?.childNodes ?? []) copy.append(node.cloneNode(true));
81
+ return copy;
82
+ } : void 0;
74
83
  const editorCode = typeof window === "undefined" ? void 0 : import("../editor/setup.js");
75
84
  const ready = shallowRef(false);
76
85
  const active = shallowRef(/* @__PURE__ */ new Set());
@@ -116,6 +125,10 @@ const _sfc_main = /*@__PURE__*/ defineComponent({
116
125
  codeLanguages: props.codeLanguages,
117
126
  extensions: props.extensions,
118
127
  upload: props.upload,
128
+ imageIcons: {
129
+ replace: slotIcon("replace"),
130
+ remove: slotIcon("remove")
131
+ },
119
132
  links: props.links,
120
133
  onChange: (doc) => model.value = doc,
121
134
  onState: (state) => {
@@ -208,14 +221,20 @@ const _sfc_main = /*@__PURE__*/ defineComponent({
208
221
  "data-part": "writer-host",
209
222
  hidden: !ready.value
210
223
  }, null, 8, _hoisted_4),
211
- __props.name && (ready.value || __props.mode !== "source") ? (openBlock(), createElementBlock("input", {
224
+ _ctx.$slots["image-replace"] || _ctx.$slots["image-remove"] ? (openBlock(), createElementBlock("div", {
212
225
  key: 2,
226
+ ref_key: "iconSource",
227
+ ref: iconSource,
228
+ hidden: ""
229
+ }, [createElementVNode("span", _hoisted_5, [renderSlot(_ctx.$slots, "image-replace")]), createElementVNode("span", _hoisted_6, [renderSlot(_ctx.$slots, "image-remove")])], 512)) : createCommentVNode("v-if", true),
230
+ __props.name && (ready.value || __props.mode !== "source") ? (openBlock(), createElementBlock("input", {
231
+ key: 3,
213
232
  type: "hidden",
214
233
  name: __props.name,
215
234
  value: model.value
216
- }, null, 8, _hoisted_5)) : createCommentVNode("v-if", true),
235
+ }, null, 8, _hoisted_7)) : createCommentVNode("v-if", true),
217
236
  __props.upload ? (openBlock(), createElementBlock("input", {
218
- key: 3,
237
+ key: 4,
219
238
  ref_key: "picker",
220
239
  ref: picker,
221
240
  type: "file",
@@ -28,11 +28,17 @@ type __VLS_Props = {
28
28
  /** Extra CodeMirror extensions. Read once, on mount. */
29
29
  extensions?: Extension;
30
30
  };
31
+ type __VLS_Slots = {
32
+ /** An image card's Replace button content, e.g. an icon. Its word stays the accessible name. */
33
+ "image-replace"?(): unknown;
34
+ /** An image card's Remove button content, e.g. an icon. Its word stays the accessible name. */
35
+ "image-remove"?(): unknown;
36
+ };
31
37
  type __VLS_ModelProps = {
32
38
  modelValue?: string;
33
39
  };
34
40
  type __VLS_PublicProps = __VLS_Props & __VLS_ModelProps;
35
- declare const __VLS_export: import("vue").DefineComponent<__VLS_PublicProps, {
41
+ declare const __VLS_base: import("vue").DefineComponent<__VLS_PublicProps, {
36
42
  /** True once CodeMirror has replaced the server-rendered fallback. */
37
43
  ready: import("vue").ShallowRef<boolean, boolean>;
38
44
  /** Formatting at the cursor. */
@@ -66,5 +72,11 @@ declare const __VLS_export: import("vue").DefineComponent<__VLS_PublicProps, {
66
72
  "onUpdate:modelValue"?: ((value: string) => any) | undefined;
67
73
  onUploadError?: ((error: unknown, file: File) => any) | undefined;
68
74
  }>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
75
+ declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
69
76
  declare const _default: typeof __VLS_export;
77
+ type __VLS_WithSlots<T, S> = T & {
78
+ new (): {
79
+ $slots: S;
80
+ };
81
+ };
70
82
  export { _default as default };
@@ -73,9 +73,7 @@ const _sfc_main = /*@__PURE__*/ defineComponent({
73
73
  unavailable: name === "undo" && !__props.editor?.canUndo || name === "redo" && !__props.editor?.canRedo
74
74
  })));
75
75
  const disabled = computed(() => !__props.editor?.ready);
76
- function buttonsIn(el) {
77
- return [...el.querySelectorAll("button")];
78
- }
76
+ const toolbarItems = useTemplateRef("toolbarItems");
79
77
  const last = shallowRef();
80
78
  const tabStop = computed(() => last.value && __props.items.includes(last.value) ? last.value : __props.items[0]);
81
79
  function rove(target) {
@@ -84,14 +82,18 @@ const _sfc_main = /*@__PURE__*/ defineComponent({
84
82
  }
85
83
  function onKeydown(event) {
86
84
  if (!root.value || !(event.target instanceof HTMLButtonElement)) return;
87
- const list = buttonsIn(root.value);
88
- const index = list.indexOf(event.target);
85
+ const list = toolbarItems.value;
86
+ const index = list?.indexOf(event.target);
87
+ if (index === void 0 || index === -1) return;
89
88
  const rtl = getComputedStyle(root.value).direction === "rtl";
90
89
  const step = {
91
90
  ArrowRight: rtl ? -1 : 1,
92
91
  ArrowLeft: rtl ? 1 : -1
93
92
  }[event.key];
94
- const target = event.key === "Home" ? list[0] : event.key === "End" ? list.at(-1) : step ? list[(index + step + list.length) % list.length] : void 0;
93
+ let target;
94
+ if (event.key === "Home") target = list?.[0];
95
+ else if (event.key === "End") target = list?.at(-1);
96
+ else if (step) target = list?.[(index + step + list.length) % list.length];
95
97
  if (!target) return;
96
98
  event.preventDefault();
97
99
  rove(target);
@@ -114,6 +116,9 @@ const _sfc_main = /*@__PURE__*/ defineComponent({
114
116
  key: button.name,
115
117
  type: "button",
116
118
  "data-part": "writer-toolbar-item",
119
+ ref_for: true,
120
+ ref_key: "toolbarItems",
121
+ ref: toolbarItems,
117
122
  "data-command": button.name,
118
123
  tabindex: button.name === tabStop.value ? 0 : -1,
119
124
  "aria-label": button.label,
package/dist/config.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { WriterTranslations, WriterTranslationsInput } from "./translations.js";
2
- import { ParserOptions } from "./parse.js";
2
+ import { ParserOptions } from "./parser-options.js";
3
+ import "./parse.js";
3
4
  import { App, Component, ComputedRef, InjectionKey, Ref } from "vue";
4
5
  export interface WriterBlock {
5
6
  /** Rendered for `::name` in content. Receives the attributes as props and the body as slots. */
@@ -0,0 +1,24 @@
1
+ # @humanonlyweb/writer
2
+
3
+ > Markdown editor and renderer for Vue 3 and Nuxt: CodeMirror editing with a live preview, Comark parsing, blocks as your own Vue components. SSR-safe; store the Markdown, render a document parsed on save. Nuxt names: `<WriterEditor>`, `<WriterToolbar>`, `<WriterContent>`; in plain Vue, import them from `@humanonlyweb/writer`.
4
+
5
+ ## Guides
6
+
7
+ - [Introduction](./index.md): A Markdown editor and renderer for Vue 3 and Nuxt.
8
+ - [Installation](./installation.md): Nuxt module or Vue plugin.
9
+ - [Blocks](./blocks.md): Your Vue components, written in Markdown.
10
+ - [Images](./images.md): Images, figures and uploads.
11
+ - [Storing documents](./storing.md): Store the Markdown, render a document parsed on save.
12
+ - [Parsing](./parsing.md): Markdown to a document, anywhere.
13
+ - [Word count](./word-count.md): Words a reader sees, and minutes to read them.
14
+ - [Styling](./styling.md): Tokens, hooks, and your site's CSS.
15
+ - [Localisation](./localisation.md): Every string the components show or announce.
16
+ - [Security](./security.md): Content is untrusted.
17
+ - [Limitations](./limitations.md): What it doesn't do yet.
18
+ - [Changelog](./changelog.md): Changes in each release.
19
+
20
+ ## Components
21
+
22
+ - [Editor](./components/editor.md): Markdown in, a live preview while you write.
23
+ - [Toolbar](./components/toolbar.md): Formatting buttons for an editor.
24
+ - [Content](./components/content.md): Markdown, rendered with your components.
@@ -0,0 +1,64 @@
1
+ # Blocks
2
+
3
+ > Your Vue components, written in Markdown.
4
+
5
+ ## Writing one
6
+
7
+ Attributes become props, `#name` sections become slots:
8
+
9
+ ```md
10
+ ::callout{type="warning"}
11
+ #title
12
+ Heads up
13
+ #default
14
+ Body with **Markdown**.
15
+ ::
16
+ ```
17
+
18
+ ```vue
19
+ <script setup lang="ts">
20
+ // `::callout` renders components/blocks/Callout.vue, in the editor and on the page.
21
+ // Type / on an empty line for the block menu.
22
+ const body = ref(`::callout{type="warning"}
23
+ Click me to edit my source.
24
+ ::
25
+
26
+ `);
27
+ </script>
28
+
29
+ <template>
30
+ <div class="writer-demo">
31
+ <WriterEditor v-model="body" label="Body" />
32
+ </div>
33
+ </template>
34
+ ```
35
+
36
+ ## Registering
37
+
38
+ In Nuxt, every component in `components/blocks/` is a block: `Callout.vue` is `::callout`, `media/Video.vue` is `::media-video`. They load on demand.
39
+
40
+ In Vue, pass them to `createWriter({ blocks: { callout: Callout } })`.
41
+
42
+ The slash menu's labels and snippets go in `app.config.ts` (or `{ component, label, snippet }` in Vue):
43
+
44
+ ```ts
45
+ export default defineAppConfig({
46
+ writer: {
47
+ blocks: {
48
+ callout: { label: "Callout", snippet: '::callout{type="${note}"}\n${}\n::' },
49
+ },
50
+ },
51
+ });
52
+ ```
53
+
54
+ Snippets use CodeMirror's syntax: `${}` is where the cursor lands, `${name}` a field Tab moves to.
55
+
56
+ ## Unknown blocks
57
+
58
+ Only registered blocks render. Anything else renders its content alone, so a removed block never breaks a page.
59
+
60
+ GitHub alerts (`> [!NOTE]`) render as a blockquote, or as your `note` block if you register one.
61
+
62
+ ## In the editor
63
+
64
+ Blocks render inside the editor through the app, not the page around it: they get app-level plugins and `provide`s, but nothing provided by a parent of `<WriterEditor>`. Declare a `__node` prop to receive the block's raw node.
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ > Changes in each release.
4
+
5
+ ## 0.2.0 (2026-11-23)
6
+
7
+ - feat: image cards' Replace and Remove take icons from the editor's image-replace and image-remove slots (copied into each card, built outside Vue), their words staying the accessible names; tests use the platform's Mod key and a Tab target Safari reaches, so the suite passes on macOS too (0.2.0)
8
+ - chore: update dependencies and improve editor functionality
9
+
10
+ ## 0.1.1 (2026-11-02)
11
+
12
+ - chore: bump version to 0.1.1 in package.json
13
+ - Editor: italic works inside words, marks skip edge spaces, code fences fit backticks, blocks keep blank lines around them, read-only cards stay read-only; docs demos for every command and read-only
14
+ - Editor: headings, quotes and lists from the toolbar leave the cursor after their marks
15
+ - fix: remove Nuxt auto-import reference from code example in storing.md
16
+ - chore: update @humanonlyweb/ui dependency version to allow minor updates
17
+ - Update favicon and logo assets; modify site manifest for branding consistency
18
+ - Add a docs site at writer.humanonlyweb.com, built from the playground; the package ships its pages as Markdown in dist/docs
19
+
20
+ ## 0.1.0 (2026-10-28)
21
+
22
+ First release.