@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/docs/api.md DELETED
@@ -1,258 +0,0 @@
1
- # @humanonlyweb/writer API reference
2
-
3
- Complete reference for this version. Written for people and coding agents: every export, prop and hook is listed here. The README has the guide.
4
-
5
- ## Rules
6
-
7
- - Store the Markdown; it is the source of truth. Optionally store the parsed document beside it as a cache, parsed on the server when saving (`parseWriterDocument` in Nuxt, `createParser` elsewhere), with `writerParserVersion`, and render it with `<WriterContent :value="document">`. Re-parse when the stored version differs.
8
- - Parse with the same options everywhere: the Nuxt module's `parser`, `createWriter({ parser })`, and server-side `createParser(options)`.
9
- - Before saving, wait for the editor's `uploading` to be `0`. Until then the Markdown holds `#upload-…` placeholders (unique, so a leftover one never receives a later upload).
10
- - Only native Markdown elements and registered blocks render. To render a component from Markdown, register it as a block; don't parse HTML.
11
- - Load a different document by changing the editor's `key`. A `v-model` change is applied as an edit.
12
- - Don't import from `dist/` paths. Use the entry points below.
13
-
14
- ## Entry points
15
-
16
- | Import | Contains |
17
- | --- | --- |
18
- | `@humanonlyweb/writer` | Components, setup, word count, rendering. Vue required. |
19
- | `@humanonlyweb/writer/parse` | Parser, sanitizer, word count. No Vue, no DOM: runs anywhere. |
20
- | `@humanonlyweb/writer/nuxt` | Nuxt module. |
21
- | `@humanonlyweb/writer/core.css` | Styles, in `@layer humanonlyweb-writer`. The Nuxt module injects it. |
22
-
23
- ## Nuxt module
24
-
25
- ```ts
26
- export default defineNuxtConfig({
27
- modules: ["@humanonlyweb/writer/nuxt"],
28
- writer: {
29
- blocks: "blocks",
30
- components: { a: "NuxtLink" },
31
- css: true,
32
- parser: { highlight: true },
33
- },
34
- });
35
- ```
36
-
37
- | Option | Type | Default | Description |
38
- | --- | --- | --- | --- |
39
- | `blocks` | `string \| false` | `"blocks"` | Folder in each layer's `components/` whose `.vue` files become blocks: `Callout.vue` → `::callout`, `media/Video.vue` → `::media-video`. Loaded on demand. The app's layer wins over extended layers. |
40
- | `components` | `Record<string, string>` | `{}` | Native element → component name, app-wide, e.g. `{ a: "NuxtLink", img: "NuxtImg" }`. Any component Nuxt registers (`#components`). Applies to `<WriterContent>` and to blocks rendered in the editor. |
41
- | `css` | `boolean` | `true` | Inject `core.css`. |
42
- | `parser` | `ParserOptions` without `plugins` | `{}` | Options for Markdown parsed by the app and by `parseWriterDocument`. |
43
-
44
- Registers `<WriterContent>`, `<WriterEditor>` and `<WriterToolbar>` globally.
45
-
46
- Server auto-imports (Nitro):
47
-
48
- - `parseWriterDocument(markdown: string): Promise<MarkdownDocument>`: `createParser` with the module's `parser` options.
49
- - `writerParserVersion: string`: this package's version and a hash of the `parser` options. Store it with each parsed document; a stored one with another value is due for parsing again.
50
- - `countWords(markdown: string): number`.
51
-
52
- `app.config.ts`:
53
-
54
- ```ts
55
- export default defineAppConfig({
56
- writer: {
57
- blocks: { callout: { label: "Callout", snippet: '::callout{type="${note}"}\n${}\n::' } },
58
- translations: { editor: "Éditeur", commands: { bold: "Gras" } },
59
- },
60
- });
61
- ```
62
-
63
- `blocks.<name>.label` is the slash menu label (default: the name). `blocks.<name>.snippet` is what the slash menu inserts, in CodeMirror snippet syntax: `${}` is the cursor, `${name}` a field Tab moves to (default: an empty block). `translations` takes any keys from [Translations](#translations).
64
-
65
- ## Vue setup
66
-
67
- ```ts
68
- import { createWriter } from "@humanonlyweb/writer";
69
- import "@humanonlyweb/writer/core.css";
70
-
71
- app.use(createWriter({ blocks: { callout: Callout }, components: { a: RouterLink } }));
72
- ```
73
-
74
- `createWriter(options?: WriterOptions)` returns a Vue plugin. Config is per app, so nothing leaks between SSR requests. Without it, the components use the defaults.
75
-
76
- `WriterOptions`:
77
-
78
- | Key | Type | Description |
79
- | --- | --- | --- |
80
- | `blocks` | `Record<string, Component \| WriterBlock>` | Blocks by Markdown name. Keys are kebab-cased: `{ InfoBox }` is `::info-box`. |
81
- | `components` | `Record<string, Component>` | Native element overrides, e.g. `{ a: RouterLink, img: AppImage }`. |
82
- | `parser` | `ParserOptions` | Used when `<WriterContent>` or the editor parses Markdown in the app. |
83
- | `translations` | `WriterTranslationsInput \| Ref<WriterTranslationsInput>` | Partial overrides of the built-in text. A ref keeps it live. |
84
-
85
- `WriterBlock`: `{ component: Component; label?: string; snippet?: string }`, as in `app.config` above.
86
-
87
- Also exported:
88
-
89
- - `useWriterConfig(): WriterConfig`: the resolved config (`blocks`, `components`, `parser`, `translations`).
90
- - `useTranslations(): ComputedRef<WriterTranslations>`: English with the app's overrides on top.
91
- - `WRITER_CONFIG_KEY`: the injection key, for providing a config yourself.
92
- - `defaultTranslations`: the English text.
93
-
94
- ## `<WriterEditor>`
95
-
96
- Server-renders the content as it will read (a `<textarea>` in `mode="source"`); CodeMirror loads in the browser and takes over.
97
-
98
- | Prop | Type | Description |
99
- | --- | --- | --- |
100
- | `v-model` | `string` | The Markdown. |
101
- | `label` | `string` | Accessible name. Default: the `editor` translation. |
102
- | `labelledby` | `string` | Id of the element naming the editor, instead of `label`. |
103
- | `describedby` | `string` | Id of a hint or error. |
104
- | `name` | `string` | Form field name: the Markdown is submitted with its form. |
105
- | `placeholder` | `string` | |
106
- | `readonly` | `boolean` | |
107
- | `mode` | `"live" \| "source"` | `live` (default): renders blocks, images and formatting in place. `source`: plain Markdown. |
108
- | `upload` | `(file: File) => Promise<string>` | Uploads a pasted, dropped or picked file, resolving to its URL. Enables files. |
109
- | `links` | `(query: string) => LinkSuggestion[] \| Promise<LinkSuggestion[]>` | Suggests link targets after `](`. `LinkSuggestion` is `{ label, url }`. |
110
- | `codeLanguages` | `readonly LanguageDescription[]` | Highlighting in fenced code, e.g. `languages` from `@codemirror/language-data`. |
111
- | `extensions` | `Extension` | Extra CodeMirror extensions. Read once, on mount. |
112
-
113
- Events: `focus`, `blur`, `upload-error(error: unknown, file: File)` (the placeholder has been removed, or a card's previous image restored).
114
-
115
- Exposed (through a template ref):
116
-
117
- | Member | Type | Description |
118
- | --- | --- | --- |
119
- | `ready` | `boolean` | CodeMirror has loaded. |
120
- | `active` | `ReadonlySet<CommandName>` | Formatting at the cursor. |
121
- | `canUpload` | `boolean` | `upload` is set. |
122
- | `canUndo`, `canRedo` | `boolean` | |
123
- | `uploading` | `number` | Uploads in progress. Save when it's `0`. |
124
- | `run(command)` | `(command: CommandName) => boolean` | Applies a command. `image` opens the file picker with `upload`, else inserts an empty image. |
125
- | `insert(text)` | `(text: string) => void` | Replaces the selection. |
126
- | `insertFiles(files)` | `(files: readonly File[]) => boolean` | Uploads and inserts files at the cursor. |
127
- | `focus()` | `() => void` | |
128
- | `view()` | `() => EditorView \| undefined` | The CodeMirror view. |
129
-
130
- Keyboard (`Mod` is Ctrl or ⌘): `Enter` starts a paragraph (a blank line, as published; in a quote, a paragraph inside it; in a list, a new item; in code, a newline), `Shift-Enter` breaks the line inside a paragraph (`\` at the line end, hidden in live preview), `Mod-B` bold, `Mod-I` italic, `Mod-E` code, `Mod-K` link, `Mod-Shift-X` strikethrough, `Mod-Alt-1`…`3` headings, `Mod-Shift-7`/`8`/`9` numbered/bulleted/task list, `Mod-Alt-F` footnote, `Mod-Z`/`Mod-Shift-Z` undo/redo, `/` on an empty line opens the block menu, `Mod-]`/`Mod-[` indent. Tab leaves the editor. Pasting a URL over a selection links it.
131
-
132
- Live preview behaviour: formatting marks show only in the element being edited, line marks (`#`, `>`, `-`) on the cursor's line. Blocks render with your components and open as framed source when clicked or arrowed into. Images alone on a line are cards (caption, alt text, drop/choose/replace); arrowing onto one selects it, Backspace/Delete removes it, Enter adds a paragraph after it. Leaving the editor shows everything as published. Several files pasted or dropped at once upload side by side, in order.
133
-
134
- ## `<WriterToolbar>`
135
-
136
- | Prop | Type | Description |
137
- | --- | --- | --- |
138
- | `editor` | `ToolbarEditor \| null \| undefined` | The editor's template ref. |
139
- | `items` | `readonly CommandName[]` | Commands in order. Default: `heading2`, `heading3`, `bold`, `italic`, `link`, `code`, `quote`, `bulletList`, `orderedList`, `codeBlock`, `image`. |
140
- | `label` | `string` | Accessible name. Default: the `toolbar` translation. |
141
-
142
- Slot `item`, props `{ command: CommandName; label: string; active: boolean }`: a button's content, e.g. an icon. The label stays its accessible name.
143
-
144
- `ToolbarEditor` is what the toolbar needs: `{ ready; active; canUndo?; canRedo?; run(command) }`. Implement it to drive the toolbar from something else.
145
-
146
- `CommandName`: `bold`, `italic`, `strikethrough`, `code`, `link`, `heading1`, `heading2`, `heading3`, `quote`, `bulletList`, `orderedList`, `taskList`, `codeBlock`, `table`, `divider`, `image`, `footnote`, `undo`, `redo`.
147
-
148
- ## `<WriterContent>`
149
-
150
- | Prop | Type | Default | Description |
151
- | --- | --- | --- | --- |
152
- | `value` | `string \| MarkdownDocument` | `""` | Markdown (parsed in the app; loads the parser), or a parsed document (renders without it). |
153
- | `components` | `Record<string, Component>` | | Native element overrides for this render, over the app's. |
154
- | `debounce` | `number` | `0` | Ms to wait before re-parsing changed Markdown. ~100 for live previews. |
155
- | `tag` | `string` | `"div"` | Wrapper element. It has `data-part="writer-content"`. |
156
-
157
- Works in SSR. A Markdown string is parsed during server rendering.
158
-
159
- ## Rendering
160
-
161
- `renderDocument(document: MarkdownDocument, options: RenderOptions): VNodeArrayChildren` renders a parsed document as Vue nodes, sanitizing it again first. `RenderOptions` is `{ blocks: Record<string, Component>; components: Record<string, Component> }`. `<WriterContent>` uses it; call it for your own wrapper.
162
-
163
- Output details:
164
-
165
- - Images get `loading="lazy"` and `decoding="async"`. An image without a URL, or with a leftover upload placeholder, isn't rendered; a file link with one renders as its text.
166
- - An image alone in its paragraph with a title (`![Alt](/a.png "Caption")`) renders as `<figure><img><figcaption>`.
167
- - A block component receives the block's attributes as props and its `#name` sections as slots. Declare a `__node` prop to receive the raw node.
168
- - A tag that isn't native or a registered block renders its children only.
169
- - Markdown that fails to parse renders nothing and is reported with `console.error`, rather than failing the page.
170
-
171
- ## Parsing (`@humanonlyweb/writer/parse`)
172
-
173
- - `createParser(options?: ParserOptions): Parse`, where `Parse` is `(markdown: string) => Promise<MarkdownDocument>`.
174
- - `parse`: `createParser()` with the defaults.
175
- - `countWords`, `readingMinutes`: see [Word count](#word-count).
176
- - `sanitize`, `isSafeUrl`, `NATIVE_TAGS`: see [Security](#security).
177
- - Types: `MarkdownDocument` (`{ nodes, frontmatter, meta }`), `ParserOptions`, `Parse`, `RangiOptions`, `Toc`, `TocLink`.
178
-
179
- `ParserOptions`:
180
-
181
- | Key | Type | Default | Description |
182
- | --- | --- | --- | --- |
183
- | `footnotes` | `boolean \| FootnotesConfig` | `true` | `[^1]` footnotes. An object sets `label` and `backRef`. |
184
- | `toc` | `boolean \| Partial<Toc>` | `false` | Table of contents in `document.meta.toc`. An object sets `depth`. |
185
- | `linkify` | `boolean` | `true` | URL-like text becomes links. |
186
- | `highlight` | `boolean \| RangiOptions` | `false` | Highlights fenced code with rangi, loaded only for documents with code. |
187
- | `plugins` | `ComarkPlugin[]` | `[]` | Extra Comark plugins. They run before sanitizing. Not serializable: not in `nuxt.config`. |
188
-
189
- Syntax: CommonMark, GFM (tables, task lists, strikethrough, autolinks), frontmatter, footnotes, GitHub alerts (`> [!NOTE]`, rendered as a `note` block if registered), Comark blocks (`::name{attr="value"}` … `::`, `#slot` sections) and attributes (`{.class #id key="value"}`). Raw HTML is text.
190
-
191
- ## Word count
192
-
193
- Both are also exported from `@humanonlyweb/writer`. Synchronous, deterministic, the same on server and client.
194
-
195
- - `countWords(markdown: string): number`: words a reader sees. Link text but not URLs; no image syntax, code, frontmatter, block fences, attributes or footnote labels. Chinese and Japanese characters count one word each.
196
- - `readingMinutes(words: number, wordsPerMinute = 230): number`: at least 1.
197
-
198
- ## Security
199
-
200
- Content is untrusted. Parsing and rendering both sanitize.
201
-
202
- - `sanitize(nodes: readonly Node[], isAllowed?: (tag: string) => boolean): Node[]`: drops `script`, `style`, `iframe`, `object`, `embed`, `link`, `meta`, `base`, `frame(set)`, `noscript`, `textarea`, `title` with their content; non-checkbox inputs; `on*` handlers; `style` attributes, except colours and font styles inside `pre` (a highlighter's; authors can't set attributes there); `srcdoc`, `formaction`, `is` and HTML-sink attributes; URLs that aren't relative, `http(s)`, `mailto` or `tel` (`data:image/…;base64` allowed for `img` `src`); bound (`:`) URL attributes. With `isAllowed`, rejected tags are replaced by their children.
203
- - `isSafeUrl(url: string): boolean`: relative, fragment, `http(s)`, `mailto` or `tel`.
204
- - `NATIVE_TAGS: ReadonlySet<string>`: the elements Markdown produces; anything else must be a registered block to render.
205
-
206
- Not removed: `class` and `id` attributes authors write with `{…}`. With untrusted authors and utility-class CSS, they can restyle parts of the page; strip them from parsed documents, or replace elements through `components`. Blocks receive attributes as written: validate any URL a block puts in an attribute other than `href` or `src`.
207
-
208
- Under a strict CSP, pass `EditorView.cspNonce.of(nonce)` in the editor's `extensions`: CodeMirror injects `<style>` elements.
209
-
210
- ## Translations
211
-
212
- `WriterTranslationsInput` is a partial `WriterTranslations`; `commands` is partial too.
213
-
214
- | Key | Default |
215
- | --- | --- |
216
- | `editor` | Markdown editor |
217
- | `toolbar` | Formatting |
218
- | `commands` | One label per `CommandName`: Bold, Italic, Strikethrough, Code, Link, Heading 1–3, Quote, Bulleted list, Numbered list, Task list, Code block, Table, Divider, Image, Footnote, Undo, Redo |
219
- | `task` | Task (a task checkbox's name until the task has text) |
220
- | `imageAlt` | Alt text |
221
- | `imageAltHint` | Describe the image for people who can't see it |
222
- | `imageCaption` | Add a caption |
223
- | `imageDrop` | Drop an image here, or |
224
- | `imageChoose` | Choose an image |
225
- | `imageUrl` | Image URL |
226
- | `imageReplace` | Replace |
227
- | `imageRemove` | Remove |
228
- | `imageUploading` | Uploading… |
229
-
230
- ## Styling
231
-
232
- Tokens, on any ancestor; they apply to the editor and to rendered content alike:
233
-
234
- | Token | Default |
235
- | --- | --- |
236
- | `--writer-h1` … `--writer-h6` | The browser's heading sizes |
237
- | `--writer-heading-weight` | `bold` |
238
- | `--writer-code-font` | `ui-monospace, SFMono-Regular, Menlo, Consolas, monospace` |
239
- | `--writer-code-size` | `0.875em` |
240
- | `--writer-quote-indent` | `1em` |
241
- | `--writer-quote-border-width` | `3px` |
242
- | `--writer-quote-border-color` | `currentColor` at 25% |
243
- | `--writer-block-inset` | `0.75em`: an open block's inline padding |
244
- | `--writer-block-background` | `currentColor` at 4%: an open block's background |
245
-
246
- Hooks:
247
-
248
- | Selector | What |
249
- | --- | --- |
250
- | `[data-part="writer-editor"]` | Editor root; `[data-mode]`, `[data-ready]`, `[data-readonly]`. |
251
- | `[data-part="writer-fallback"]` | Content (or source-mode textarea) before load. |
252
- | `[data-part="writer-host"] .cm-editor` | CodeMirror. |
253
- | `[data-part="writer-content"]` | Rendered content, also inside editor previews. |
254
- | `.cm-md-preview` (`[data-part="writer-preview"]`), `.cm-md-block-open`, `.cm-md-block-fence` | Rendered blocks; lines of a block open for editing. |
255
- | `[data-part="writer-image"]` (`.cm-md-image`), `.cm-md-image-frame`, `.cm-md-image-caption`, `.cm-md-image-alt` | Image cards; `[data-selected]`, frame `[data-empty]`, `[data-uploading]`, `[data-dropping]`. |
256
- | `.cm-md-bullet`, `.cm-md-task`, `.cm-md-quote-line`, `.cm-md-hr` | Live preview stand-ins for list, task, quote and rule syntax. |
257
- | `.cm-md-h1`…`.cm-md-h6`, `.cm-md-codeblock`, `.cm-md-strong`, `.cm-md-em`, `.cm-md-strike`, `.cm-md-code`, `.cm-md-link`, `.cm-md-quote`, `.cm-md-mark`, `.cm-md-comment` | Markdown source. |
258
- | `[data-part="writer-toolbar"]`, `[data-part="writer-toolbar-item"][data-command]` | Toolbar and its buttons; `[aria-pressed]`, `[aria-disabled]`. |