@humanonlyweb/writer 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -307
- package/dist/config.d.ts +2 -1
- package/dist/docs/README.md +24 -0
- package/dist/docs/blocks.md +64 -0
- package/dist/docs/changelog.md +17 -0
- package/dist/docs/components/content.md +51 -0
- package/dist/docs/components/editor.md +236 -0
- package/dist/docs/components/toolbar.md +146 -0
- package/dist/docs/images.md +80 -0
- package/dist/docs/index.md +86 -0
- package/dist/docs/installation.md +74 -0
- package/dist/docs/limitations.md +11 -0
- package/dist/docs/localisation.md +35 -0
- package/dist/docs/parsing.md +47 -0
- package/dist/docs/security.md +16 -0
- package/dist/docs/storing.md +105 -0
- package/dist/docs/styling.md +47 -0
- package/dist/docs/word-count.md +16 -0
- package/dist/editor/commands.js +116 -51
- package/dist/editor/images.js +24 -12
- package/dist/editor/live.js +2 -1
- package/dist/editor/setup.js +20 -1
- package/dist/index.d.ts +2 -1
- package/dist/nuxt/module.d.ts +1 -4
- package/dist/nuxt/module.js +23 -1
- package/dist/nuxt/runtime/plugin.js +2 -1
- package/dist/package.js +1 -1
- package/dist/parse.d.ts +5 -20
- package/dist/parser-options.d.ts +19 -0
- package/package.json +13 -8
- package/docs/api.md +0 -258
|
@@ -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]`. |
|
|
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.
|
package/dist/editor/commands.js
CHANGED
|
@@ -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
|
-
/**
|
|
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
|
|
24
|
+
const char = marker[0] ?? "";
|
|
8
25
|
return (state) => ({
|
|
9
26
|
...state.changeByRange((range) => {
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
if (
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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:
|
|
34
|
-
insert:
|
|
70
|
+
from: start,
|
|
71
|
+
insert: open
|
|
35
72
|
}, {
|
|
36
|
-
from:
|
|
37
|
-
insert:
|
|
73
|
+
from: end,
|
|
74
|
+
insert: close
|
|
38
75
|
}],
|
|
39
|
-
range: EditorSelection.range(
|
|
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
|
|
68
|
-
|
|
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
|
-
/**
|
|
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:
|
|
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
|
-
|
|
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
|
-
/**
|
|
244
|
-
|
|
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,
|
package/dist/editor/images.js
CHANGED
|
@@ -123,6 +123,8 @@ async function finish(view, file, token, options, previous) {
|
|
|
123
123
|
if (local) setTimeout(() => URL.revokeObjectURL(local), 3e4);
|
|
124
124
|
}
|
|
125
125
|
}
|
|
126
|
+
/** The newlines to add to `newlines` for a blank line. */
|
|
127
|
+
const gap = (newlines) => "\n".repeat(Math.max(0, 2 - newlines));
|
|
126
128
|
/**
|
|
127
129
|
* Uploads `files`, inserted at `at`, each on its own line, in one edit; or uploads the
|
|
128
130
|
* first into the image line `replace`. Placeholders go in at once and the uploads run
|
|
@@ -149,9 +151,11 @@ async function uploadFiles(view, files, options, target) {
|
|
|
149
151
|
else {
|
|
150
152
|
const { state } = view;
|
|
151
153
|
const at = Math.min("at" in target ? target.at : 0, state.doc.length);
|
|
152
|
-
const
|
|
153
|
-
const
|
|
154
|
-
const
|
|
154
|
+
const textBefore = state.sliceDoc(0, at);
|
|
155
|
+
const textAfter = state.sliceDoc(at);
|
|
156
|
+
const before = textBefore.trim() ? gap(/\n*$/.exec(textBefore)?.[0].length ?? 0) : "";
|
|
157
|
+
const after = textAfter.trim() ? gap(/^\n*/.exec(textAfter)?.[0].length ?? 0) : textAfter.startsWith("\n") ? "" : "\n";
|
|
158
|
+
const insert = before + lines.join("\n\n") + after;
|
|
155
159
|
view.dispatch({
|
|
156
160
|
changes: {
|
|
157
161
|
from: at,
|
|
@@ -221,7 +225,7 @@ var ImageCardWidget = class extends WidgetType {
|
|
|
221
225
|
/** Back to writing, on the line after the image. */
|
|
222
226
|
leave(view, dom) {
|
|
223
227
|
const { to } = this.range(view, dom);
|
|
224
|
-
if (to === view.state.doc.length) view.dispatch({
|
|
228
|
+
if (to === view.state.doc.length && !view.state.readOnly) view.dispatch({
|
|
225
229
|
changes: {
|
|
226
230
|
from: to,
|
|
227
231
|
insert: "\n"
|
|
@@ -281,14 +285,21 @@ var ImageCardWidget = class extends WidgetType {
|
|
|
281
285
|
caption,
|
|
282
286
|
alt,
|
|
283
287
|
url
|
|
284
|
-
])
|
|
285
|
-
|
|
286
|
-
event.preventDefault();
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
288
|
+
]) {
|
|
289
|
+
input.addEventListener("beforeinput", (event) => {
|
|
290
|
+
if (view.state.readOnly) event.preventDefault();
|
|
291
|
+
});
|
|
292
|
+
input.addEventListener("keydown", (event) => {
|
|
293
|
+
if (event.key === "Enter" || event.key === "Escape") {
|
|
294
|
+
event.preventDefault();
|
|
295
|
+
this.leave(view, root);
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
}
|
|
290
299
|
if (upload) {
|
|
291
|
-
const choosePicked = () =>
|
|
300
|
+
const choosePicked = () => {
|
|
301
|
+
if (!view.state.readOnly) pickFile((file) => upload(view, file, this.range(view, root)));
|
|
302
|
+
};
|
|
292
303
|
choose.addEventListener("click", choosePicked);
|
|
293
304
|
replace.addEventListener("click", choosePicked);
|
|
294
305
|
frame.addEventListener("dragover", (event) => {
|
|
@@ -303,10 +314,11 @@ var ImageCardWidget = class extends WidgetType {
|
|
|
303
314
|
if (!file?.type.startsWith("image/")) return;
|
|
304
315
|
event.preventDefault();
|
|
305
316
|
event.stopPropagation();
|
|
306
|
-
upload(view, file, this.range(view, root));
|
|
317
|
+
if (!view.state.readOnly) upload(view, file, this.range(view, root));
|
|
307
318
|
});
|
|
308
319
|
}
|
|
309
320
|
remove.addEventListener("click", () => {
|
|
321
|
+
if (view.state.readOnly) return;
|
|
310
322
|
const { from, to } = this.range(view, root);
|
|
311
323
|
view.dispatch({
|
|
312
324
|
changes: {
|
package/dist/editor/live.js
CHANGED
|
@@ -309,6 +309,7 @@ function cardKeys(field) {
|
|
|
309
309
|
};
|
|
310
310
|
const removeOrSelect = (direction) => (view) => {
|
|
311
311
|
const { state } = view;
|
|
312
|
+
if (state.readOnly) return false;
|
|
312
313
|
const selected = selectedImage(state);
|
|
313
314
|
if (selected) {
|
|
314
315
|
const to = Math.min(selected.to + 1, state.doc.length);
|
|
@@ -347,7 +348,7 @@ function cardKeys(field) {
|
|
|
347
348
|
{
|
|
348
349
|
key: "Enter",
|
|
349
350
|
run: (view) => {
|
|
350
|
-
const selected = selectedImage(view.state);
|
|
351
|
+
const selected = !view.state.readOnly && selectedImage(view.state);
|
|
351
352
|
if (!selected) return false;
|
|
352
353
|
view.dispatch({
|
|
353
354
|
changes: {
|
package/dist/editor/setup.js
CHANGED
|
@@ -128,6 +128,16 @@ const theme = EditorView.theme({
|
|
|
128
128
|
}
|
|
129
129
|
});
|
|
130
130
|
const URL_PATTERN = /^https?:\/\/\S+$/;
|
|
131
|
+
/** Slash menu items that start a line rather than a block of their own. */
|
|
132
|
+
const LINE_STARTS = /* @__PURE__ */ new Set([
|
|
133
|
+
"heading1",
|
|
134
|
+
"heading2",
|
|
135
|
+
"heading3",
|
|
136
|
+
"bulletList",
|
|
137
|
+
"orderedList",
|
|
138
|
+
"taskList",
|
|
139
|
+
"quote"
|
|
140
|
+
]);
|
|
131
141
|
const snapshot = (state) => ({
|
|
132
142
|
active: activeCommands(state),
|
|
133
143
|
undo: undoDepth(state) > 0,
|
|
@@ -240,7 +250,15 @@ function createEditor(options) {
|
|
|
240
250
|
type: "text",
|
|
241
251
|
apply: (view, completion, start, end) => {
|
|
242
252
|
const command = item.name === "footnote" ? commands.footnote : item.name === "image" ? imageCommand : void 0;
|
|
243
|
-
if (!command)
|
|
253
|
+
if (!command) {
|
|
254
|
+
const { doc } = view.state;
|
|
255
|
+
const here = doc.lineAt(start);
|
|
256
|
+
const filled = (n) => n >= 1 && n <= doc.lines && !!doc.line(n).text.trim();
|
|
257
|
+
const block = !LINE_STARTS.has(item.name);
|
|
258
|
+
const before = block && filled(here.number - 1) ? "\n" : "";
|
|
259
|
+
const after = block && filled(here.number + 1) ? "\n" : "";
|
|
260
|
+
return snippet(before + item.snippet + after)(view, completion, start - 1, end);
|
|
261
|
+
}
|
|
244
262
|
const removeSlash = view.state.update({ changes: {
|
|
245
263
|
from: start - 1,
|
|
246
264
|
to: end
|
|
@@ -360,6 +378,7 @@ function createEditor(options) {
|
|
|
360
378
|
]),
|
|
361
379
|
EditorView.domEventHandlers({
|
|
362
380
|
paste(event, view) {
|
|
381
|
+
if (view.state.readOnly) return false;
|
|
363
382
|
const files = [...event.clipboardData?.files ?? []];
|
|
364
383
|
if (files.length && insertFiles(files)) {
|
|
365
384
|
event.preventDefault();
|
package/dist/index.d.ts
CHANGED
|
@@ -3,8 +3,9 @@ import { CommandName, WriterTranslations, WriterTranslationsInput, defaultTransl
|
|
|
3
3
|
import _default$1 from "./components/WriterEditor.vue.js";
|
|
4
4
|
import { ToolbarEditor } from "./types.js";
|
|
5
5
|
import _default$2 from "./components/WriterToolbar.vue.js";
|
|
6
|
+
import { ParserOptions } from "./parser-options.js";
|
|
6
7
|
import { countWords, readingMinutes } from "./stats.js";
|
|
7
|
-
import { MarkdownDocument
|
|
8
|
+
import { MarkdownDocument } from "./parse.js";
|
|
8
9
|
import { WRITER_CONFIG_KEY, WriterBlock, WriterConfig, WriterOptions, createWriter, useTranslations, useWriterConfig } from "./config.js";
|
|
9
10
|
import { RenderOptions, renderDocument } from "./render.js";
|
|
10
11
|
export { type CommandName, type MarkdownDocument, type ParserOptions, type RenderOptions, type ToolbarEditor, WRITER_CONFIG_KEY, type WriterBlock, type WriterConfig, _default as WriterContent, _default$1 as WriterEditor, type WriterOptions, _default$2 as WriterToolbar, type WriterTranslations, type WriterTranslationsInput, countWords, createWriter, defaultTranslations, readingMinutes, renderDocument, useTranslations, useWriterConfig };
|
package/dist/nuxt/module.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { WriterTranslationsInput } from "../translations.js";
|
|
2
|
-
import { ParserOptions } from "../
|
|
2
|
+
import { ParserOptions } from "../parser-options.js";
|
|
3
3
|
/** Auto-registered components. A test keeps it in step with `src/index.ts`. */
|
|
4
4
|
export declare const COMPONENTS: readonly ["WriterContent", "WriterEditor", "WriterToolbar"];
|
|
5
5
|
export interface ModuleOptions {
|
|
@@ -30,9 +30,6 @@ declare module "@nuxt/schema" {
|
|
|
30
30
|
interface AppConfigInput {
|
|
31
31
|
writer?: WriterAppConfig;
|
|
32
32
|
}
|
|
33
|
-
interface AppConfig {
|
|
34
|
-
writer?: WriterAppConfig;
|
|
35
|
-
}
|
|
36
33
|
}
|
|
37
34
|
declare const _default: import("@nuxt/schema").NuxtModule<ModuleOptions, ModuleOptions, false>;
|
|
38
35
|
export { _default as default };
|