@humanonlyweb/writer 0.0.0-stage → 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.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -2
  3. package/dist/components/WriterContent.d.ts +57 -0
  4. package/dist/components/WriterContent.js +114 -0
  5. package/dist/components/WriterEditor.js +232 -0
  6. package/dist/components/WriterEditor.vue.d.ts +70 -0
  7. package/dist/components/WriterToolbar.js +135 -0
  8. package/dist/components/WriterToolbar.vue.d.ts +27 -0
  9. package/dist/config.d.ts +39 -0
  10. package/dist/config.js +41 -0
  11. package/dist/docs/README.md +24 -0
  12. package/dist/docs/blocks.md +64 -0
  13. package/dist/docs/changelog.md +17 -0
  14. package/dist/docs/components/content.md +51 -0
  15. package/dist/docs/components/editor.md +236 -0
  16. package/dist/docs/components/toolbar.md +146 -0
  17. package/dist/docs/images.md +80 -0
  18. package/dist/docs/index.md +86 -0
  19. package/dist/docs/installation.md +74 -0
  20. package/dist/docs/limitations.md +11 -0
  21. package/dist/docs/localisation.md +35 -0
  22. package/dist/docs/parsing.md +47 -0
  23. package/dist/docs/security.md +16 -0
  24. package/dist/docs/storing.md +105 -0
  25. package/dist/docs/styling.md +47 -0
  26. package/dist/docs/word-count.md +16 -0
  27. package/dist/editor/commands.d.ts +1 -0
  28. package/dist/editor/commands.js +359 -0
  29. package/dist/editor/images.d.ts +1 -0
  30. package/dist/editor/images.js +400 -0
  31. package/dist/editor/live.d.ts +2 -0
  32. package/dist/editor/live.js +411 -0
  33. package/dist/editor/setup.d.ts +9 -0
  34. package/dist/editor/setup.js +485 -0
  35. package/dist/index.d.ts +11 -0
  36. package/dist/index.js +8 -0
  37. package/dist/load-parser.js +12 -0
  38. package/dist/nuxt/module.d.ts +35 -0
  39. package/dist/nuxt/module.js +114 -0
  40. package/dist/nuxt/runtime/plugin.d.ts +2 -0
  41. package/dist/nuxt/runtime/plugin.js +25 -0
  42. package/dist/nuxt/runtime/server/parse.d.ts +12 -0
  43. package/dist/nuxt/runtime/server/parse.js +15 -0
  44. package/dist/package.js +3 -0
  45. package/dist/parse.d.ts +16 -0
  46. package/dist/parse.js +62 -0
  47. package/dist/parser-options.d.ts +19 -0
  48. package/dist/placeholder.js +5 -0
  49. package/dist/render.d.ts +10 -0
  50. package/dist/render.js +97 -0
  51. package/dist/sanitize.d.ts +11 -0
  52. package/dist/sanitize.js +139 -0
  53. package/dist/stats.d.ts +8 -0
  54. package/dist/stats.js +17 -0
  55. package/dist/styles/core.css +275 -0
  56. package/dist/translations.d.ts +26 -0
  57. package/dist/translations.js +47 -0
  58. package/dist/types.d.ts +9 -0
  59. package/package.json +101 -4
@@ -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.
@@ -0,0 +1 @@
1
+ import { EditorState } from "@codemirror/state";
@@ -0,0 +1,359 @@
1
+ import { syntaxTree } from "@codemirror/language";
2
+ import { EditorSelection } from "@codemirror/state";
3
+ // src/editor/commands.ts
4
+ const userEvent = "input.format";
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
+ */
23
+ function toggleInline(marker) {
24
+ const char = marker[0] ?? "";
25
+ return (state) => ({
26
+ ...state.changeByRange((range) => {
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
+ }
68
+ return {
69
+ changes: [{
70
+ from: start,
71
+ insert: open
72
+ }, {
73
+ from: end,
74
+ insert: close
75
+ }],
76
+ range: EditorSelection.range(start + open.length, end + open.length)
77
+ };
78
+ }),
79
+ userEvent
80
+ });
81
+ }
82
+ function selectedLines(state) {
83
+ const lines = /* @__PURE__ */ new Map();
84
+ for (const range of state.selection.ranges) for (let pos = range.from; pos <= range.to;) {
85
+ const line = state.doc.lineAt(pos);
86
+ lines.set(line.number, line);
87
+ pos = line.to + 1;
88
+ }
89
+ return [...lines.values()];
90
+ }
91
+ /** Any block prefix: a heading, quote or list marker. Setting one replaces the others. */
92
+ const BLOCK = /^([ \t]*)(?:#{1,6}[ \t]+|>[ \t]?|(?:[-*+]|\d+[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)/;
93
+ /** The block prefix a line has, without its indentation. */
94
+ const prefixOf = (text) => BLOCK.exec(text)?.[0].trimStart() ?? "";
95
+ /**
96
+ * Gives each selected line the block prefix `prefix` returns (`## `, `- `, `> `),
97
+ * replacing any other. When every line already has it, removes it instead.
98
+ */
99
+ function toggleLinePrefix(prefix) {
100
+ return (state) => {
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;
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
+ };
123
+ return {
124
+ changes,
125
+ selection: EditorSelection.create(state.selection.ranges.map((range) => EditorSelection.range(place(range.anchor), place(range.head))), state.selection.mainIndex),
126
+ userEvent
127
+ };
128
+ };
129
+ }
130
+ function link(state) {
131
+ return {
132
+ ...state.changeByRange((range) => {
133
+ const text = state.sliceDoc(range.from, range.to);
134
+ if (/^https?:\/\/\S+$/.test(text)) {
135
+ const insert = `[](${text})`;
136
+ return {
137
+ changes: {
138
+ from: range.from,
139
+ to: range.to,
140
+ insert
141
+ },
142
+ range: EditorSelection.cursor(range.from + 1)
143
+ };
144
+ }
145
+ const label = text || "text";
146
+ const insert = `[${label}](url)`;
147
+ const start = text ? range.from + label.length + 3 : range.from + 1;
148
+ return {
149
+ changes: {
150
+ from: range.from,
151
+ to: range.to,
152
+ insert
153
+ },
154
+ range: EditorSelection.range(start, start + (text ? 3 : label.length))
155
+ };
156
+ }),
157
+ userEvent
158
+ };
159
+ }
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
+ */
165
+ function insertBlock(block, cursor = block.length) {
166
+ return (state) => {
167
+ const { to } = state.selection.main;
168
+ const line = state.doc.lineAt(to);
169
+ const empty = !line.text.trim();
170
+ const from = empty ? line.from : line.to;
171
+ const end = empty ? line.to : from;
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));
177
+ return {
178
+ changes: {
179
+ from,
180
+ to: end,
181
+ insert: before + block + after
182
+ },
183
+ selection: EditorSelection.cursor(from + before.length + cursor),
184
+ userEvent: "input.insert"
185
+ };
186
+ };
187
+ }
188
+ function codeBlock(state) {
189
+ const { from, to } = state.selection.main;
190
+ if (from === to) return insertBlock("```\n\n```", 4)(state);
191
+ const start = state.doc.lineAt(from).from;
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
+ }]);
200
+ return {
201
+ changes,
202
+ selection: EditorSelection.range(changes.mapPos(from, 1), changes.mapPos(to, -1)),
203
+ userEvent
204
+ };
205
+ }
206
+ /** Adds the next free `[^n]` at the cursor and its definition at the end, with the cursor there. */
207
+ function footnote(state) {
208
+ const doc = state.doc.toString();
209
+ const used = new Set([...doc.matchAll(/\[\^([^\]\s]+)\]/g)].map((match) => match[1]));
210
+ let label = 1;
211
+ while (used.has(String(label))) label++;
212
+ const reference = `[^${label}]`;
213
+ const at = state.selection.main.to;
214
+ const before = at === doc.length ? doc + reference : doc;
215
+ const definition = `${before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n"}[^${label}]: `;
216
+ return {
217
+ changes: [{
218
+ from: at,
219
+ insert: reference
220
+ }, {
221
+ from: doc.length,
222
+ insert: definition
223
+ }],
224
+ selection: EditorSelection.cursor(doc.length + reference.length + definition.length),
225
+ scrollIntoView: true,
226
+ userEvent: "input.insert"
227
+ };
228
+ }
229
+ /** Where Enter is just a newline: code, tables, raw HTML. */
230
+ const LITERAL = /* @__PURE__ */ new Set([
231
+ "FencedCode",
232
+ "CodeBlock",
233
+ "Table",
234
+ "HTMLBlock",
235
+ "CommentBlock",
236
+ "ProcessingInstructionBlock",
237
+ "LinkReference"
238
+ ]);
239
+ /** A block's `::name` or closing `::` line. */
240
+ const BLOCK_FENCE = /^\s*:{2,}/;
241
+ const QUOTE_PREFIX = /^[ \t]*(?:>[ \t]?)+/;
242
+ /** Up to a list item's text, quote markers included: `> - `, ` 1. `. */
243
+ const LIST_PREFIX = /^((?:[ \t]*>)*)([ \t]*(?:[-*+]|\d+[.)])[ \t]+)/;
244
+ function inFrontmatter(state, pos) {
245
+ const doc = state.doc.toString();
246
+ if (!/^---\r?\n/.test(doc)) return false;
247
+ const end = doc.slice(3).search(/\n---[ \t]*(?:\r?\n|$)/);
248
+ return end >= 0 && pos <= end + 4;
249
+ }
250
+ function placeAt(state, pos) {
251
+ const line = state.doc.lineAt(pos);
252
+ if (!line.text.trim() || BLOCK_FENCE.test(line.text) || inFrontmatter(state, pos)) return null;
253
+ for (let node = syntaxTree(state).resolveInner(pos, -1); node; node = node.parent) {
254
+ if (LITERAL.has(node.name)) return null;
255
+ if (/^(?:ATX|Setext)Heading/.test(node.name)) return { kind: "heading" };
256
+ if (node.name === "ListItem") {
257
+ const [, quotes = "", marker] = LIST_PREFIX.exec(line.text) ?? [];
258
+ const leading = /^[ \t]*/.exec(line.text)?.[0] ?? "";
259
+ return {
260
+ kind: "list",
261
+ indent: quotes + " ".repeat(marker?.length ?? leading.length)
262
+ };
263
+ }
264
+ if (node.name === "Blockquote") {
265
+ const prefix = QUOTE_PREFIX.exec(line.text)?.[0] ?? "";
266
+ if (!line.text.slice(prefix.length).trim()) return null;
267
+ return {
268
+ kind: "quote",
269
+ prefix
270
+ };
271
+ }
272
+ }
273
+ return { kind: "prose" };
274
+ }
275
+ /** Inserts what `text` returns for each cursor's place; `null` anywhere leaves it to the defaults. */
276
+ function insertAtPlace(text) {
277
+ return (state) => {
278
+ const inserts = state.selection.ranges.map((range) => {
279
+ const place = range.empty ? placeAt(state, range.head) : null;
280
+ return place && text(place);
281
+ });
282
+ if (inserts.some((insert) => insert === null)) return null;
283
+ let index = 0;
284
+ return {
285
+ ...state.changeByRange((range) => {
286
+ const insert = inserts[index++] ?? "";
287
+ return {
288
+ changes: {
289
+ from: range.head,
290
+ insert
291
+ },
292
+ range: EditorSelection.cursor(range.head + insert.length)
293
+ };
294
+ }),
295
+ userEvent: "input"
296
+ };
297
+ };
298
+ }
299
+ /**
300
+ * Enter: a new paragraph, as the page will show it. A single newline would read as a
301
+ * new line here but join the paragraph when published. In a list, lang-markdown's
302
+ * Enter adds an item instead.
303
+ */
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 : ""}`);
310
+ const commands = {
311
+ bold: toggleInline("**"),
312
+ italic: toggleInline("*"),
313
+ strikethrough: toggleInline("~~"),
314
+ code: toggleInline("`"),
315
+ link,
316
+ heading1: toggleLinePrefix(() => "# "),
317
+ heading2: toggleLinePrefix(() => "## "),
318
+ heading3: toggleLinePrefix(() => "### "),
319
+ quote: toggleLinePrefix(() => "> "),
320
+ bulletList: toggleLinePrefix(() => "- "),
321
+ orderedList: toggleLinePrefix((i) => `${i + 1}. `),
322
+ taskList: toggleLinePrefix(() => "- [ ] "),
323
+ codeBlock,
324
+ table: insertBlock("| Column | Column |\n| --- | --- |\n| | |", 2),
325
+ divider: insertBlock("---\n\n"),
326
+ footnote
327
+ };
328
+ const NODE_COMMANDS = {
329
+ StrongEmphasis: "bold",
330
+ Emphasis: "italic",
331
+ Strikethrough: "strikethrough",
332
+ InlineCode: "code",
333
+ Link: "link",
334
+ ATXHeading1: "heading1",
335
+ SetextHeading1: "heading1",
336
+ ATXHeading2: "heading2",
337
+ SetextHeading2: "heading2",
338
+ ATXHeading3: "heading3",
339
+ Blockquote: "quote",
340
+ OrderedList: "orderedList",
341
+ FencedCode: "codeBlock",
342
+ Table: "table"
343
+ };
344
+ /** Formatting at the cursor, for toolbar pressed states. */
345
+ function activeCommands(state) {
346
+ const active = /* @__PURE__ */ new Set();
347
+ const { head } = state.selection.main;
348
+ for (let node = syntaxTree(state).resolveInner(head, -1); node; node = node.parent) {
349
+ const name = NODE_COMMANDS[node.name];
350
+ if (name) active.add(name);
351
+ if (node.name === "ListItem" && !active.has("taskList") && !active.has("bulletList")) {
352
+ if (node.getChild("Task")) active.add("taskList");
353
+ else if (node.parent?.name === "BulletList") active.add("bulletList");
354
+ }
355
+ }
356
+ if (active.has("taskList") || active.has("bulletList")) active.delete("orderedList");
357
+ return active;
358
+ }
359
+ export { activeCommands, commands, insertBlock, lineBreak, newParagraph };
@@ -0,0 +1 @@
1
+ import { EditorView, WidgetType } from "@codemirror/view";