@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.
@@ -0,0 +1,74 @@
1
+ # Installation
2
+
3
+ > Nuxt module or Vue plugin.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ bun add @humanonlyweb/writer
9
+ ```
10
+
11
+ ## Nuxt
12
+
13
+ The components are auto-imported, `core.css` is added, and every component in `components/blocks/` becomes a block.
14
+
15
+ ```ts
16
+ // nuxt.config.ts
17
+ export default defineNuxtConfig({
18
+ modules: ["@humanonlyweb/writer/nuxt"],
19
+ writer: {
20
+ blocks: "blocks", // folder in components/; false for none
21
+ components: { a: "NuxtLink" }, // render native elements with your components
22
+ css: true, // inject core.css
23
+ parser: { highlight: true }, // see Parsing
24
+ },
25
+ });
26
+ ```
27
+
28
+ On the server, `parseWriterDocument`, `writerParserVersion` and `countWords` 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 | What it does |
42
+ | -------------- | -------------------------------------------------------------------------------------------------- |
43
+ | `blocks` | Components authors can use, by Markdown name: `{ callout }` is `::callout`. 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 browser. |
46
+ | `translations` | The built-in text. See [Localisation](/localisation). |
47
+
48
+ `useWriterConfig()` reads the config in your own components, and `WRITER_CONFIG_KEY` provides one yourself.
49
+
50
+ ## Use it
51
+
52
+ ```vue
53
+ <script setup lang="ts">
54
+ const body = ref("");
55
+ const editor = useTemplateRef("editor");
56
+ </script>
57
+
58
+ <template>
59
+ <WriterToolbar :editor="editor" />
60
+ <WriterEditor ref="editor" v-model="body" label="Post body" />
61
+ <WriterContent :value="body" />
62
+ </template>
63
+ ```
64
+
65
+ In plain Vue, import `WriterEditor`, `WriterToolbar` and `WriterContent` from `@humanonlyweb/writer`.
66
+
67
+ ## AI agents
68
+
69
+ The package ships these docs as Markdown, matching the installed version. Point your agent at them in `AGENTS.md` or `CLAUDE.md`:
70
+
71
+ ```md
72
+ For @humanonlyweb/writer, read node_modules/@humanonlyweb/writer/dist/docs/README.md
73
+ before using it. It indexes a page per topic: components, parsing, storing documents.
74
+ ```
@@ -0,0 +1,11 @@
1
+ # Limitations
2
+
3
+ > What it doesn't do yet.
4
+
5
+ - **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.
6
+ - **Indented content** (four spaces in, outside a block) stays Markdown: it's code, or deeply nested list content.
7
+ - **Blocks in the editor** render through the app, not the page: they get app-level plugins and `provide`s, but nothing a parent of `<WriterEditor>` provides.
8
+ - **Footnotes inside a block** are numbered within that block in the editor; the page numbers them across the document.
9
+ - **An empty image card** is 16:9 until a file is chosen.
10
+ - **Chinese, Japanese and Korean input** (IME composition) hasn't been tested by hand yet.
11
+ - **Tested** in Chromium, Firefox and WebKit, automatically. Touch devices and screen readers haven't been tested by hand yet.
@@ -0,0 +1,35 @@
1
+ # Localisation
2
+
3
+ > Every string the components show or announce.
4
+
5
+ Pass only what you change. In Nuxt, use `app.config.ts`:
6
+
7
+ ```ts
8
+ export default defineAppConfig({
9
+ writer: {
10
+ translations: { editor: "Éditeur", commands: { bold: "Gras" } },
11
+ },
12
+ });
13
+ ```
14
+
15
+ In Vue, `createWriter({ translations })`. A ref keeps it live, e.g. when the reader switches language.
16
+
17
+ | Key | Default |
18
+ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
19
+ | `editor` | Markdown editor |
20
+ | `toolbar` | Formatting |
21
+ | `commands` | A label per command: Bold, Italic, Strikethrough, Code, Link, Heading 1–3, Quote, Bulleted list, Numbered list, Task list, Code block, Table, Divider, Image, Footnote, Undo, Redo |
22
+ | `task` | Task (a task checkbox's name before it has text) |
23
+ | `imageAlt` | Alt text |
24
+ | `imageAltHint` | Describe the image for people who can't see it |
25
+ | `imageCaption` | Add a caption |
26
+ | `imageDrop` | Drop an image here, or |
27
+ | `imageChoose` | Choose an image |
28
+ | `imageUrl` | Image URL |
29
+ | `imageReplace` | Replace |
30
+ | `imageRemove` | Remove |
31
+ | `imageUploading` | Uploading… |
32
+
33
+ `defaultTranslations` has them all; `useTranslations()` gives the resolved set.
34
+
35
+ Each line takes its own text direction, so right-to-left and mixed text work.
@@ -0,0 +1,47 @@
1
+ # Parsing
2
+
3
+ > Markdown to a document, anywhere.
4
+
5
+ ## Parser
6
+
7
+ `@humanonlyweb/writer/parse` has no Vue and no DOM: it runs on the server, in a worker, in a script.
8
+
9
+ ```ts
10
+ import { createParser } from "@humanonlyweb/writer/parse";
11
+
12
+ const parse = createParser({ highlight: true, toc: true });
13
+ const document = await parse(markdown);
14
+ document.meta.toc; // { links: [{ id, text, depth, children }] }
15
+ ```
16
+
17
+ `parse` is `createParser()` with the defaults. Use the same options everywhere you parse: the Nuxt module's `parser`, `createWriter({ parser })` and the server.
18
+
19
+ ## Options
20
+
21
+ | Option | Default | What it does |
22
+ | ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
23
+ | `footnotes` | `true` | `[^1]` footnotes. An object sets `label` and `backRef`. |
24
+ | `highlight` | `false` | Highlights fenced code with [rangi](https://comark.dev/plugins/built-in/rangi). An object sets `theme`, `lineNumbers`. Loads only for documents with code. |
25
+ | `toc` | `false` | Table of contents in `meta.toc`. An object sets `depth`. |
26
+ | `linkify` | `true` | URL-like text becomes links. |
27
+ | `plugins` | `[]` | Other Comark plugins, e.g. `comark/plugins/shiki`. They run before sanitizing. Not in `nuxt.config`: they aren't serializable, so parse on the server. |
28
+
29
+ ## Syntax
30
+
31
+ CommonMark and GFM (tables, task lists, strikethrough, autolinks), frontmatter, footnotes, GitHub alerts, [blocks](/blocks) and `{.class #id key="value"}` attributes. Raw HTML is text.
32
+
33
+ A blank line starts a paragraph; a `\` at the end of a line breaks it. The editor's Enter and Shift+Enter write those for you.
34
+
35
+ ## Dark mode code
36
+
37
+ rangi colours code inline for its light theme and puts the dark one in `--shiki-dark`:
38
+
39
+ ```css
40
+ @media (prefers-color-scheme: dark) {
41
+ .shiki span {
42
+ color: var(--shiki-dark) !important;
43
+ }
44
+ }
45
+ ```
46
+
47
+ This site does exactly that.
@@ -0,0 +1,16 @@
1
+ # Security
2
+
3
+ > Content is untrusted.
4
+
5
+ - Raw HTML is text.
6
+ - Only Markdown's own elements and registered blocks render. App-wide components can't be reached from Markdown.
7
+ - `script`, `style`, `iframe`, `object` and similar are removed, with their content. So are `on*` handlers, `style` attributes (except a highlighter's colours inside code) and URLs that aren't relative, `http(s)`, `mailto` or `tel`.
8
+ - `<WriterContent>` sanitizes again before rendering, so a stored document is safe even if it didn't come from this parser.
9
+
10
+ The checks are exported from `@humanonlyweb/writer/parse`: `sanitize(nodes, isAllowed?)`, `isSafeUrl(url)` and `NATIVE_TAGS`.
11
+
12
+ ## What's left to you
13
+
14
+ - Authors can set `class` and `id` with `{…}`. With untrusted authors and utility-class CSS (`fixed inset-0`), that's enough to restyle the page: strip them from parsed documents, or render those elements through `components`.
15
+ - Blocks get attributes as written. Validate any URL your block puts in an attribute other than `href` or `src`.
16
+ - CodeMirror injects `<style>` elements. Under a strict CSP, pass `EditorView.cspNonce.of(nonce)` in `extensions`.
@@ -0,0 +1,105 @@
1
+ # Storing documents
2
+
3
+ > Store the Markdown, render a document parsed on save.
4
+
5
+ ## The short version
6
+
7
+ Store the Markdown: it's the source of truth. Parse it on the server when saving, store that too, and render it. Visitors then download neither the parser nor the editor.
8
+
9
+ | Column | Type | Description |
10
+ | --------------------- | ---- | -------------------------------------------------------------- |
11
+ | `body` | text | What the editor produces. |
12
+ | `body_document` | json | Optional cache: the parsed document, for rendering. |
13
+ | `body_parser_version` | text | `writerParserVersion` when parsed: tells you when to re-parse. |
14
+
15
+ ```ts
16
+ // server/api/posts/[id].put.ts
17
+ await db.posts.update(id, {
18
+ body: input.body,
19
+ body_document: await parseWriterDocument(input.body),
20
+ body_parser_version: writerParserVersion,
21
+ word_count: countWords(input.body),
22
+ });
23
+ ```
24
+
25
+ ```vue
26
+ <WriterContent :value="post.body_document" />
27
+ ```
28
+
29
+ Outside Nuxt, `createParser(options)` from `@humanonlyweb/writer/parse` with the options your app renders with.
30
+
31
+ ## Re-parsing
32
+
33
+ The parsed document is derived, so it can go stale. `writerParserVersion` is this package's version plus a hash of your `parser` options. When a stored one differs, parse the `body` again: on read, or in a batch after deploying. Outside Nuxt, do the same with the package version and your options.
34
+
35
+ ## Drafts and published versions
36
+
37
+ On a real site, an autosave shouldn't change the live page. Keep the working copy on the article, and freeze what readers see as a revision when publishing:
38
+
39
+ ```sql
40
+ -- The working copy the editor autosaves. Readers see published_revision_id.
41
+ CREATE TABLE articles (
42
+ id TEXT PRIMARY KEY,
43
+ slug TEXT NOT NULL UNIQUE,
44
+ section_id TEXT NOT NULL REFERENCES sections (id),
45
+ byline_id TEXT NOT NULL REFERENCES personas (id),
46
+ headline TEXT NOT NULL,
47
+ dek TEXT NOT NULL,
48
+ body TEXT NOT NULL, -- the editor's Markdown
49
+ updated_at TEXT NOT NULL,
50
+ published_revision_id TEXT REFERENCES revisions (id),
51
+ published_at TEXT
52
+ );
53
+
54
+ -- Published versions, frozen: everything readers see.
55
+ CREATE TABLE revisions (
56
+ id TEXT PRIMARY KEY,
57
+ article_id TEXT NOT NULL REFERENCES articles (id) ON DELETE CASCADE,
58
+ section_id TEXT NOT NULL REFERENCES sections (id),
59
+ byline_id TEXT NOT NULL REFERENCES personas (id),
60
+ headline TEXT NOT NULL,
61
+ dek TEXT NOT NULL,
62
+ body TEXT NOT NULL,
63
+ body_document TEXT NOT NULL, -- JSON: parseWriterDocument(body)
64
+ body_parser_version TEXT NOT NULL, -- writerParserVersion when parsed
65
+ word_count INTEGER NOT NULL,
66
+ created_at TEXT NOT NULL
67
+ );
68
+
69
+ -- Uploads. The files live in storage; the Markdown holds their url.
70
+ CREATE TABLE assets (
71
+ id TEXT PRIMARY KEY,
72
+ url TEXT NOT NULL UNIQUE,
73
+ type TEXT NOT NULL,
74
+ bytes INTEGER NOT NULL,
75
+ created_at TEXT NOT NULL
76
+ );
77
+ ```
78
+
79
+ Publishing parses the working copy into a new revision, then points the article at it:
80
+
81
+ ```ts
82
+ async function publish(article: Article) {
83
+ const revision = {
84
+ id: crypto.randomUUID(),
85
+ articleId: article.id,
86
+ // …section, byline, headline, dek and body, copied from the article
87
+ body: article.body,
88
+ bodyDocument: await parseWriterDocument(article.body),
89
+ bodyParserVersion: writerParserVersion,
90
+ wordCount: countWords(article.body),
91
+ createdAt: new Date().toISOString(),
92
+ };
93
+ await db.revisions.insert(revision);
94
+ await db.articles.update(article.id, {
95
+ publishedRevisionId: revision.id,
96
+ publishedAt: article.publishedAt ?? revision.createdAt,
97
+ });
98
+ }
99
+ ```
100
+
101
+ Before saving or publishing, wait for the editor's `uploading` to be `0`: until then the Markdown holds placeholders.
102
+
103
+ ## Keep metadata out of the body
104
+
105
+ Headlines, slugs, dates and authors go in their own columns, not frontmatter, so you can query and index them. Things templates add around the body (related links, ads) stay out of it too. If editors place something by hand mid-article, make it a [block](/blocks).
@@ -0,0 +1,47 @@
1
+ # Styling
2
+
3
+ > Tokens, hooks, and your site's CSS.
4
+
5
+ ## Your CSS wins
6
+
7
+ `core.css` is in `@layer humanonlyweb-writer`, so anything you write overrides it. It styles the editor's Markdown source and gives the editor and rendered content one type scale: a heading is the same size in both.
8
+
9
+ Style rendered content (`[data-part="writer-content"]`) as your site's prose. The editor's previews use the same wrapper, so they pick it up too.
10
+
11
+ ## Tokens
12
+
13
+ Set them on any ancestor; the editor and content both follow.
14
+
15
+ | Token | Default | Description |
16
+ | ------------------------------------------------------------ | ------------------------- | ----------------------------------------------------------------------------------- |
17
+ | `--writer-h1` … `--writer-h6` | The browser's | Heading sizes. |
18
+ | `--writer-heading-weight` | `bold` | |
19
+ | `--writer-code-font`, `--writer-code-size` | `ui-monospace`, `0.875em` | Inline and block code. |
20
+ | `--writer-quote-indent` | `1em` | Quotes. |
21
+ | `--writer-quote-border-width`, `--writer-quote-border-color` | `3px`, text at 25% | |
22
+ | `--writer-block-inset`, `--writer-block-background` | `0.75em`, text at 4% | An open block's padding and background: match your blocks' and the text won't jump. |
23
+
24
+ ```css
25
+ :root {
26
+ --writer-h2: 1.6rem;
27
+ --writer-code-font: "JetBrains Mono", monospace;
28
+ --writer-block-inset: 1.25rem;
29
+ --writer-block-background: #fbf6e3;
30
+ }
31
+ ```
32
+
33
+ If your prose CSS sets heading sizes directly, set these to the same values, or the editor won't match.
34
+
35
+ ## Hooks
36
+
37
+ | Selector | Description |
38
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
39
+ | `[data-part="writer-editor"]` | Editor root: `[data-mode]`, `[data-ready]`, `[data-readonly]`. |
40
+ | `[data-part="writer-fallback"]` | What shows before CodeMirror loads. |
41
+ | `[data-part="writer-host"] .cm-editor` | CodeMirror. |
42
+ | `[data-part="writer-content"]` | Rendered content, on the page and in the editor's previews. |
43
+ | `.cm-md-preview`, `.cm-md-block-open`, `.cm-md-block-fence` | Rendered blocks, and the lines of a block open for editing. |
44
+ | `[data-part="writer-image"]`, `.cm-md-image-frame`, `.cm-md-image-caption`, `.cm-md-image-alt` | Image cards: `[data-selected]`; the frame `[data-empty]`, `[data-uploading]`, `[data-dropping]`; `.cm-md-image-actions button[data-icon]` with the `image-replace` and `image-remove` slots. |
45
+ | `.cm-md-bullet`, `.cm-md-task`, `.cm-md-quote-line`, `.cm-md-hr` | Live preview's stand-ins for list, task, quote and rule syntax. |
46
+ | `.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. |
47
+ | `[data-part="writer-toolbar"]`, `[data-part="writer-toolbar-item"][data-command]` | Toolbar and buttons: `[aria-pressed]`, `[aria-disabled]`. |
@@ -0,0 +1,16 @@
1
+ # Word count
2
+
3
+ > Words a reader sees, and minutes to read them.
4
+
5
+ ```ts
6
+ import { countWords, readingMinutes } from "@humanonlyweb/writer";
7
+
8
+ const words = countWords(markdown);
9
+ readingMinutes(words); // at least 1, at 230 words a minute
10
+ ```
11
+
12
+ `countWords(markdown)` counts words, and `readingMinutes(words, wordsPerMinute = 230)` turns them into minutes.
13
+
14
+ It 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 a word per character.
15
+
16
+ It's synchronous, fast enough for every keystroke, and gives the same answer on the server and in the browser, so it's safe to render during SSR. In Nuxt it's auto-imported on the server too: store it with the document.
@@ -2,41 +2,78 @@ import { syntaxTree } from "@codemirror/language";
2
2
  import { EditorSelection } from "@codemirror/state";
3
3
  // src/editor/commands.ts
4
4
  const userEvent = "input.format";
5
- /** Wraps each selection in `marker`, or unwraps it when it's already wrapped. */
5
+ /** How many `char`s run from `pos`, backwards (`-1`) or forwards (`1`), within `from`…`to`. */
6
+ function run(state, pos, char, direction, from = 0, to = state.doc.length) {
7
+ let count = 0;
8
+ for (let at = direction < 0 ? pos - 1 : pos; at >= from && at < to && state.sliceDoc(at, at + 1) === char; at += direction) count++;
9
+ return count;
10
+ }
11
+ /**
12
+ * Whether a run of `marker`'s character, `count` long on both sides, includes `marker`:
13
+ * `*` in `***` (bold and italic) but not in `**` (bold alone).
14
+ */
15
+ const includes = (marker, count) => marker === "*" ? count % 2 === 1 : count >= marker.length;
16
+ /** Characters to take off each side to remove `marker` from a run `count` long. */
17
+ const removable = (marker, count) => marker === "`" ? count : marker.length;
18
+ /**
19
+ * Wraps each selection in `marker`, or unwraps it when it's already wrapped. Spaces at
20
+ * the selection's edges stay outside: `** word**` wouldn't be bold. Code containing
21
+ * backticks gets a longer fence.
22
+ */
6
23
  function toggleInline(marker) {
7
- const size = marker.length;
24
+ const char = marker[0] ?? "";
8
25
  return (state) => ({
9
26
  ...state.changeByRange((range) => {
10
- const before = state.sliceDoc(range.from - size, range.from);
11
- const after = state.sliceDoc(range.to, range.to + size);
12
- if (before === marker && after === marker) return {
13
- changes: [{
14
- from: range.from - size,
15
- to: range.from
16
- }, {
17
- from: range.to,
18
- to: range.to + size
19
- }],
20
- range: EditorSelection.range(range.from - size, range.to - size)
21
- };
22
- const text = state.sliceDoc(range.from, range.to);
23
- if (text.length >= size * 2 && text.startsWith(marker) && text.endsWith(marker)) return {
24
- changes: {
25
- from: range.from,
26
- to: range.to,
27
- insert: text.slice(size, -size)
28
- },
29
- range: EditorSelection.range(range.from, range.to - size * 2)
30
- };
27
+ const { from, to } = range;
28
+ const outside = Math.min(run(state, from, char, -1), run(state, to, char, 1));
29
+ if (outside && includes(marker, outside)) {
30
+ const n = removable(marker, outside);
31
+ return {
32
+ changes: [{
33
+ from: from - n,
34
+ to: from
35
+ }, {
36
+ from: to,
37
+ to: to + n
38
+ }],
39
+ range: EditorSelection.range(from - n, to - n)
40
+ };
41
+ }
42
+ const inside = Math.min(run(state, from, char, 1, from, to), run(state, to, char, -1, from, to));
43
+ if (inside && to - from > inside * 2 && includes(marker, inside)) {
44
+ const n = removable(marker, inside);
45
+ return {
46
+ changes: [{
47
+ from,
48
+ to: from + n
49
+ }, {
50
+ from: to - n,
51
+ to
52
+ }],
53
+ range: EditorSelection.range(from, to - n * 2)
54
+ };
55
+ }
56
+ const text = state.sliceDoc(from, to);
57
+ const start = from + (text.length - text.trimStart().length);
58
+ const end = Math.max(start, to - (text.length - text.trimEnd().length));
59
+ let open = marker;
60
+ let close = marker;
61
+ if (marker === "`") {
62
+ const inner = state.sliceDoc(start, end);
63
+ const longest = Math.max(0, ...(inner.match(/`+/g) ?? []).map((ticks) => ticks.length));
64
+ const pad = inner.startsWith("`") || inner.endsWith("`") ? " " : "";
65
+ open = "`".repeat(longest + 1) + pad;
66
+ close = pad + "`".repeat(longest + 1);
67
+ }
31
68
  return {
32
69
  changes: [{
33
- from: range.from,
34
- insert: marker
70
+ from: start,
71
+ insert: open
35
72
  }, {
36
- from: range.to,
37
- insert: marker
73
+ from: end,
74
+ insert: close
38
75
  }],
39
- range: EditorSelection.range(range.from + size, range.to + size)
76
+ range: EditorSelection.range(start + open.length, end + open.length)
40
77
  };
41
78
  }),
42
79
  userEvent
@@ -62,17 +99,30 @@ const prefixOf = (text) => BLOCK.exec(text)?.[0].trimStart() ?? "";
62
99
  function toggleLinePrefix(prefix) {
63
100
  return (state) => {
64
101
  const lines = selectedLines(state);
102
+ const tree = syntaxTree(state);
103
+ const inCode = (pos) => {
104
+ for (let node = tree.resolveInner(pos, 1); node; node = node.parent) if (node.name === "FencedCode" || node.name === "CodeBlock") return true;
105
+ return false;
106
+ };
107
+ if (lines.some((line) => inCode(line.from))) return null;
65
108
  const remove = lines.every((line, i) => prefixOf(line.text) === prefix(i));
109
+ const edits = lines.map((line, i) => {
110
+ const match = BLOCK.exec(line.text);
111
+ const indent = match?.[1] ?? "";
112
+ return {
113
+ from: line.from,
114
+ to: line.from + (match?.[0].length ?? 0),
115
+ insert: remove ? indent : indent + prefix(i)
116
+ };
117
+ });
118
+ const changes = state.changes(edits);
119
+ const place = (pos) => {
120
+ const edit = edits.find((e) => pos >= e.from && pos <= e.to);
121
+ return edit ? changes.mapPos(edit.from) + edit.insert.length : changes.mapPos(pos, 1);
122
+ };
66
123
  return {
67
- changes: lines.map((line, i) => {
68
- const match = BLOCK.exec(line.text);
69
- const indent = match?.[1] ?? "";
70
- return {
71
- from: line.from,
72
- to: line.from + (match?.[0].length ?? 0),
73
- insert: remove ? indent : indent + prefix(i)
74
- };
75
- }),
124
+ changes,
125
+ selection: EditorSelection.create(state.selection.ranges.map((range) => EditorSelection.range(place(range.anchor), place(range.head))), state.selection.mainIndex),
76
126
  userEvent
77
127
  };
78
128
  };
@@ -107,19 +157,28 @@ function link(state) {
107
157
  userEvent
108
158
  };
109
159
  }
110
- /** Inserts `block` on lines of its own after the selection, with the cursor at `cursor` inside it. */
160
+ /**
161
+ * Inserts `block` on lines of its own after the selection, with the cursor at `cursor`
162
+ * inside it, and a blank line before and after it, so it doesn't join the paragraph
163
+ * around it (a table would take the next line as a row, an image would sit inside it).
164
+ */
111
165
  function insertBlock(block, cursor = block.length) {
112
166
  return (state) => {
113
167
  const { to } = state.selection.main;
114
168
  const line = state.doc.lineAt(to);
115
169
  const empty = !line.text.trim();
116
170
  const from = empty ? line.from : line.to;
171
+ const end = empty ? line.to : from;
117
172
  const before = empty ? "" : "\n\n";
173
+ const following = /^\n*/.exec(state.sliceDoc(end, end + 2))?.[0].length ?? 0;
174
+ const atEnd = !state.sliceDoc(end).trim();
175
+ const own = /\n*$/.exec(block)?.[0].length ?? 0;
176
+ const after = atEnd ? "" : "\n".repeat(Math.max(0, 2 - following - own));
118
177
  return {
119
178
  changes: {
120
179
  from,
121
- to: empty ? line.to : from,
122
- insert: before + block
180
+ to: end,
181
+ insert: before + block + after
123
182
  },
124
183
  selection: EditorSelection.cursor(from + before.length + cursor),
125
184
  userEvent: "input.insert"
@@ -131,14 +190,16 @@ function codeBlock(state) {
131
190
  if (from === to) return insertBlock("```\n\n```", 4)(state);
132
191
  const start = state.doc.lineAt(from).from;
133
192
  const end = state.doc.lineAt(to).to;
193
+ const changes = state.changes([{
194
+ from: start,
195
+ insert: "```\n"
196
+ }, {
197
+ from: end,
198
+ insert: "\n```"
199
+ }]);
134
200
  return {
135
- changes: [{
136
- from: start,
137
- insert: "```\n"
138
- }, {
139
- from: end,
140
- insert: "\n```"
141
- }],
201
+ changes,
202
+ selection: EditorSelection.range(changes.mapPos(from, 1), changes.mapPos(to, -1)),
142
203
  userEvent
143
204
  };
144
205
  }
@@ -191,6 +252,7 @@ function placeAt(state, pos) {
191
252
  if (!line.text.trim() || BLOCK_FENCE.test(line.text) || inFrontmatter(state, pos)) return null;
192
253
  for (let node = syntaxTree(state).resolveInner(pos, -1); node; node = node.parent) {
193
254
  if (LITERAL.has(node.name)) return null;
255
+ if (/^(?:ATX|Setext)Heading/.test(node.name)) return { kind: "heading" };
194
256
  if (node.name === "ListItem") {
195
257
  const [, quotes = "", marker] = LIST_PREFIX.exec(line.text) ?? [];
196
258
  const leading = /^[ \t]*/.exec(line.text)?.[0] ?? "";
@@ -239,12 +301,15 @@ function insertAtPlace(text) {
239
301
  * new line here but join the paragraph when published. In a list, lang-markdown's
240
302
  * Enter adds an item instead.
241
303
  */
242
- const newParagraph = insertAtPlace((place) => place.kind === "prose" ? "\n\n" : place.kind === "quote" ? `\n${place.prefix.trimEnd()}\n${place.prefix}` : null);
243
- /** Shift+Enter: a line break inside the paragraph (`\` at the end of the line). */
244
- const lineBreak = insertAtPlace((place) => `\\\n${place.kind === "quote" ? place.prefix : place.kind === "list" ? place.indent : ""}`);
304
+ const newParagraph = insertAtPlace((place) => place.kind === "prose" || place.kind === "heading" ? "\n\n" : place.kind === "quote" ? `\n${place.prefix.trimEnd()}\n${place.prefix}` : null);
305
+ /**
306
+ * Shift+Enter: a line break inside the paragraph (`\` at the end of the line). A heading
307
+ * can't hold one, so there it starts a paragraph, like Enter.
308
+ */
309
+ const lineBreak = insertAtPlace((place) => place.kind === "heading" ? "\n\n" : `\\\n${place.kind === "quote" ? place.prefix : place.kind === "list" ? place.indent : ""}`);
245
310
  const commands = {
246
311
  bold: toggleInline("**"),
247
- italic: toggleInline("_"),
312
+ italic: toggleInline("*"),
248
313
  strikethrough: toggleInline("~~"),
249
314
  code: toggleInline("`"),
250
315
  link,