@humanonlyweb/writer 0.0.0-stage → 0.1.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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +355 -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 +38 -0
  10. package/dist/config.js +41 -0
  11. package/dist/editor/commands.d.ts +1 -0
  12. package/dist/editor/commands.js +294 -0
  13. package/dist/editor/images.d.ts +1 -0
  14. package/dist/editor/images.js +388 -0
  15. package/dist/editor/live.d.ts +2 -0
  16. package/dist/editor/live.js +410 -0
  17. package/dist/editor/setup.d.ts +9 -0
  18. package/dist/editor/setup.js +466 -0
  19. package/dist/index.d.ts +10 -0
  20. package/dist/index.js +8 -0
  21. package/dist/load-parser.js +12 -0
  22. package/dist/nuxt/module.d.ts +38 -0
  23. package/dist/nuxt/module.js +92 -0
  24. package/dist/nuxt/runtime/plugin.d.ts +2 -0
  25. package/dist/nuxt/runtime/plugin.js +24 -0
  26. package/dist/nuxt/runtime/server/parse.d.ts +12 -0
  27. package/dist/nuxt/runtime/server/parse.js +15 -0
  28. package/dist/package.js +3 -0
  29. package/dist/parse.d.ts +31 -0
  30. package/dist/parse.js +62 -0
  31. package/dist/placeholder.js +5 -0
  32. package/dist/render.d.ts +10 -0
  33. package/dist/render.js +97 -0
  34. package/dist/sanitize.d.ts +11 -0
  35. package/dist/sanitize.js +139 -0
  36. package/dist/stats.d.ts +8 -0
  37. package/dist/stats.js +17 -0
  38. package/dist/styles/core.css +275 -0
  39. package/dist/translations.d.ts +26 -0
  40. package/dist/translations.js +47 -0
  41. package/dist/types.d.ts +9 -0
  42. package/docs/api.md +258 -0
  43. package/package.json +96 -4
@@ -0,0 +1,294 @@
1
+ import { syntaxTree } from "@codemirror/language";
2
+ import { EditorSelection } from "@codemirror/state";
3
+ // src/editor/commands.ts
4
+ const userEvent = "input.format";
5
+ /** Wraps each selection in `marker`, or unwraps it when it's already wrapped. */
6
+ function toggleInline(marker) {
7
+ const size = marker.length;
8
+ return (state) => ({
9
+ ...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
+ };
31
+ return {
32
+ changes: [{
33
+ from: range.from,
34
+ insert: marker
35
+ }, {
36
+ from: range.to,
37
+ insert: marker
38
+ }],
39
+ range: EditorSelection.range(range.from + size, range.to + size)
40
+ };
41
+ }),
42
+ userEvent
43
+ });
44
+ }
45
+ function selectedLines(state) {
46
+ const lines = /* @__PURE__ */ new Map();
47
+ for (const range of state.selection.ranges) for (let pos = range.from; pos <= range.to;) {
48
+ const line = state.doc.lineAt(pos);
49
+ lines.set(line.number, line);
50
+ pos = line.to + 1;
51
+ }
52
+ return [...lines.values()];
53
+ }
54
+ /** Any block prefix: a heading, quote or list marker. Setting one replaces the others. */
55
+ const BLOCK = /^([ \t]*)(?:#{1,6}[ \t]+|>[ \t]?|(?:[-*+]|\d+[.)])[ \t]+(?:\[[ xX]\][ \t]+)?)/;
56
+ /** The block prefix a line has, without its indentation. */
57
+ const prefixOf = (text) => BLOCK.exec(text)?.[0].trimStart() ?? "";
58
+ /**
59
+ * Gives each selected line the block prefix `prefix` returns (`## `, `- `, `> `),
60
+ * replacing any other. When every line already has it, removes it instead.
61
+ */
62
+ function toggleLinePrefix(prefix) {
63
+ return (state) => {
64
+ const lines = selectedLines(state);
65
+ const remove = lines.every((line, i) => prefixOf(line.text) === prefix(i));
66
+ 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
+ }),
76
+ userEvent
77
+ };
78
+ };
79
+ }
80
+ function link(state) {
81
+ return {
82
+ ...state.changeByRange((range) => {
83
+ const text = state.sliceDoc(range.from, range.to);
84
+ if (/^https?:\/\/\S+$/.test(text)) {
85
+ const insert = `[](${text})`;
86
+ return {
87
+ changes: {
88
+ from: range.from,
89
+ to: range.to,
90
+ insert
91
+ },
92
+ range: EditorSelection.cursor(range.from + 1)
93
+ };
94
+ }
95
+ const label = text || "text";
96
+ const insert = `[${label}](url)`;
97
+ const start = text ? range.from + label.length + 3 : range.from + 1;
98
+ return {
99
+ changes: {
100
+ from: range.from,
101
+ to: range.to,
102
+ insert
103
+ },
104
+ range: EditorSelection.range(start, start + (text ? 3 : label.length))
105
+ };
106
+ }),
107
+ userEvent
108
+ };
109
+ }
110
+ /** Inserts `block` on lines of its own after the selection, with the cursor at `cursor` inside it. */
111
+ function insertBlock(block, cursor = block.length) {
112
+ return (state) => {
113
+ const { to } = state.selection.main;
114
+ const line = state.doc.lineAt(to);
115
+ const empty = !line.text.trim();
116
+ const from = empty ? line.from : line.to;
117
+ const before = empty ? "" : "\n\n";
118
+ return {
119
+ changes: {
120
+ from,
121
+ to: empty ? line.to : from,
122
+ insert: before + block
123
+ },
124
+ selection: EditorSelection.cursor(from + before.length + cursor),
125
+ userEvent: "input.insert"
126
+ };
127
+ };
128
+ }
129
+ function codeBlock(state) {
130
+ const { from, to } = state.selection.main;
131
+ if (from === to) return insertBlock("```\n\n```", 4)(state);
132
+ const start = state.doc.lineAt(from).from;
133
+ const end = state.doc.lineAt(to).to;
134
+ return {
135
+ changes: [{
136
+ from: start,
137
+ insert: "```\n"
138
+ }, {
139
+ from: end,
140
+ insert: "\n```"
141
+ }],
142
+ userEvent
143
+ };
144
+ }
145
+ /** Adds the next free `[^n]` at the cursor and its definition at the end, with the cursor there. */
146
+ function footnote(state) {
147
+ const doc = state.doc.toString();
148
+ const used = new Set([...doc.matchAll(/\[\^([^\]\s]+)\]/g)].map((match) => match[1]));
149
+ let label = 1;
150
+ while (used.has(String(label))) label++;
151
+ const reference = `[^${label}]`;
152
+ const at = state.selection.main.to;
153
+ const before = at === doc.length ? doc + reference : doc;
154
+ const definition = `${before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n"}[^${label}]: `;
155
+ return {
156
+ changes: [{
157
+ from: at,
158
+ insert: reference
159
+ }, {
160
+ from: doc.length,
161
+ insert: definition
162
+ }],
163
+ selection: EditorSelection.cursor(doc.length + reference.length + definition.length),
164
+ scrollIntoView: true,
165
+ userEvent: "input.insert"
166
+ };
167
+ }
168
+ /** Where Enter is just a newline: code, tables, raw HTML. */
169
+ const LITERAL = /* @__PURE__ */ new Set([
170
+ "FencedCode",
171
+ "CodeBlock",
172
+ "Table",
173
+ "HTMLBlock",
174
+ "CommentBlock",
175
+ "ProcessingInstructionBlock",
176
+ "LinkReference"
177
+ ]);
178
+ /** A block's `::name` or closing `::` line. */
179
+ const BLOCK_FENCE = /^\s*:{2,}/;
180
+ const QUOTE_PREFIX = /^[ \t]*(?:>[ \t]?)+/;
181
+ /** Up to a list item's text, quote markers included: `> - `, ` 1. `. */
182
+ const LIST_PREFIX = /^((?:[ \t]*>)*)([ \t]*(?:[-*+]|\d+[.)])[ \t]+)/;
183
+ function inFrontmatter(state, pos) {
184
+ const doc = state.doc.toString();
185
+ if (!/^---\r?\n/.test(doc)) return false;
186
+ const end = doc.slice(3).search(/\n---[ \t]*(?:\r?\n|$)/);
187
+ return end >= 0 && pos <= end + 4;
188
+ }
189
+ function placeAt(state, pos) {
190
+ const line = state.doc.lineAt(pos);
191
+ if (!line.text.trim() || BLOCK_FENCE.test(line.text) || inFrontmatter(state, pos)) return null;
192
+ for (let node = syntaxTree(state).resolveInner(pos, -1); node; node = node.parent) {
193
+ if (LITERAL.has(node.name)) return null;
194
+ if (node.name === "ListItem") {
195
+ const [, quotes = "", marker] = LIST_PREFIX.exec(line.text) ?? [];
196
+ const leading = /^[ \t]*/.exec(line.text)?.[0] ?? "";
197
+ return {
198
+ kind: "list",
199
+ indent: quotes + " ".repeat(marker?.length ?? leading.length)
200
+ };
201
+ }
202
+ if (node.name === "Blockquote") {
203
+ const prefix = QUOTE_PREFIX.exec(line.text)?.[0] ?? "";
204
+ if (!line.text.slice(prefix.length).trim()) return null;
205
+ return {
206
+ kind: "quote",
207
+ prefix
208
+ };
209
+ }
210
+ }
211
+ return { kind: "prose" };
212
+ }
213
+ /** Inserts what `text` returns for each cursor's place; `null` anywhere leaves it to the defaults. */
214
+ function insertAtPlace(text) {
215
+ return (state) => {
216
+ const inserts = state.selection.ranges.map((range) => {
217
+ const place = range.empty ? placeAt(state, range.head) : null;
218
+ return place && text(place);
219
+ });
220
+ if (inserts.some((insert) => insert === null)) return null;
221
+ let index = 0;
222
+ return {
223
+ ...state.changeByRange((range) => {
224
+ const insert = inserts[index++] ?? "";
225
+ return {
226
+ changes: {
227
+ from: range.head,
228
+ insert
229
+ },
230
+ range: EditorSelection.cursor(range.head + insert.length)
231
+ };
232
+ }),
233
+ userEvent: "input"
234
+ };
235
+ };
236
+ }
237
+ /**
238
+ * Enter: a new paragraph, as the page will show it. A single newline would read as a
239
+ * new line here but join the paragraph when published. In a list, lang-markdown's
240
+ * Enter adds an item instead.
241
+ */
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 : ""}`);
245
+ const commands = {
246
+ bold: toggleInline("**"),
247
+ italic: toggleInline("_"),
248
+ strikethrough: toggleInline("~~"),
249
+ code: toggleInline("`"),
250
+ link,
251
+ heading1: toggleLinePrefix(() => "# "),
252
+ heading2: toggleLinePrefix(() => "## "),
253
+ heading3: toggleLinePrefix(() => "### "),
254
+ quote: toggleLinePrefix(() => "> "),
255
+ bulletList: toggleLinePrefix(() => "- "),
256
+ orderedList: toggleLinePrefix((i) => `${i + 1}. `),
257
+ taskList: toggleLinePrefix(() => "- [ ] "),
258
+ codeBlock,
259
+ table: insertBlock("| Column | Column |\n| --- | --- |\n| | |", 2),
260
+ divider: insertBlock("---\n\n"),
261
+ footnote
262
+ };
263
+ const NODE_COMMANDS = {
264
+ StrongEmphasis: "bold",
265
+ Emphasis: "italic",
266
+ Strikethrough: "strikethrough",
267
+ InlineCode: "code",
268
+ Link: "link",
269
+ ATXHeading1: "heading1",
270
+ SetextHeading1: "heading1",
271
+ ATXHeading2: "heading2",
272
+ SetextHeading2: "heading2",
273
+ ATXHeading3: "heading3",
274
+ Blockquote: "quote",
275
+ OrderedList: "orderedList",
276
+ FencedCode: "codeBlock",
277
+ Table: "table"
278
+ };
279
+ /** Formatting at the cursor, for toolbar pressed states. */
280
+ function activeCommands(state) {
281
+ const active = /* @__PURE__ */ new Set();
282
+ const { head } = state.selection.main;
283
+ for (let node = syntaxTree(state).resolveInner(head, -1); node; node = node.parent) {
284
+ const name = NODE_COMMANDS[node.name];
285
+ if (name) active.add(name);
286
+ if (node.name === "ListItem" && !active.has("taskList") && !active.has("bulletList")) {
287
+ if (node.getChild("Task")) active.add("taskList");
288
+ else if (node.parent?.name === "BulletList") active.add("bulletList");
289
+ }
290
+ }
291
+ if (active.has("taskList") || active.has("bulletList")) active.delete("orderedList");
292
+ return active;
293
+ }
294
+ export { activeCommands, commands, insertBlock, lineBreak, newParagraph };
@@ -0,0 +1 @@
1
+ import { EditorView, WidgetType } from "@codemirror/view";
@@ -0,0 +1,388 @@
1
+ import { UPLOAD_PLACEHOLDER, isUploadPlaceholder } from "../placeholder.js";
2
+ import { WidgetType } from "@codemirror/view";
3
+ // src/editor/images.ts
4
+ const IMAGE = /^(\s*)!\[((?:\\.|[^\]\\\n])*)\]\(\s*(<[^>\n]*>|[^\s)]*)(?:\s+"((?:\\.|[^"\\\n])*)")?\s*\)(\{[^}\n]*\})?\s*$/;
5
+ const unescape = (text) => text.replace(/\\(.)/g, "$1");
6
+ function parseImageLine(text) {
7
+ const match = IMAGE.exec(text);
8
+ if (!match) return null;
9
+ return {
10
+ indent: match[1] ?? "",
11
+ alt: unescape(match[2] ?? ""),
12
+ url: (match[3] ?? "").replace(/^<(.*)>$/, "$1"),
13
+ title: unescape(match[4] ?? ""),
14
+ attrs: match[5] ?? ""
15
+ };
16
+ }
17
+ function formatImageLine({ indent, alt, url, title, attrs }) {
18
+ const safeAlt = alt.replace(/\n/g, " ").replace(/[\\\]]/g, "\\$&");
19
+ const safeTitle = title.replace(/\n/g, " ").replace(/[\\"]/g, "\\$&");
20
+ return `${indent}![${safeAlt}](${/[\s()]/.test(url) || !url && safeTitle ? `<${url}>` : url}${safeTitle ? ` "${safeTitle}"` : ""})${attrs}`;
21
+ }
22
+ /** Width and height in an attribute block, which reserve the image's space on the page. */
23
+ function imageSize(attrs) {
24
+ const read = (name) => {
25
+ const value = new RegExp(`(?:^|[\\s{])${name}="?(\\d+)"?`).exec(attrs)?.[1];
26
+ return value ? Number(value) : void 0;
27
+ };
28
+ return {
29
+ width: read("width"),
30
+ height: read("height")
31
+ };
32
+ }
33
+ function withSize(attrs, width, height) {
34
+ return `{${[attrs.slice(1, -1).replace(/(?:^|\s)(?:width|height)="?\d+"?/g, "").trim(), `width="${width}" height="${height}"`].filter(Boolean).join(" ")}}`;
35
+ }
36
+ /** Local previews of files still uploading, by their placeholder URL. */
37
+ const previews = /* @__PURE__ */ new Map();
38
+ let uploadCount = 0;
39
+ async function sizeOf(file) {
40
+ try {
41
+ const bitmap = await createImageBitmap(file);
42
+ const size = {
43
+ width: bitmap.width,
44
+ height: bitmap.height
45
+ };
46
+ bitmap.close();
47
+ return size;
48
+ } catch {
49
+ return;
50
+ }
51
+ }
52
+ /** Where `token` is in the document, followed by the end of its URL. */
53
+ function find(view, token) {
54
+ const doc = view.state.doc.toString();
55
+ for (let at = doc.indexOf(token); at >= 0; at = doc.indexOf(token, at + 1)) if (/[)\s]/.test(doc[at + token.length] ?? "")) return at;
56
+ return -1;
57
+ }
58
+ /** A placeholder URL, unique across page loads: a leftover one in a saved document never matches. */
59
+ const nextToken = () => `${UPLOAD_PLACEHOLDER}${Date.now().toString(36)}${(++uploadCount).toString(36)}`;
60
+ /**
61
+ * The Markdown a file is while it uploads. An image shows from the local file, at its real
62
+ * size, and keeps the alt text and caption of the image it replaces.
63
+ */
64
+ async function placeholderLine(file, token, replacing) {
65
+ if (!file.type.startsWith("image/")) return `[${file.name.replace(/[[\]]/g, "")}](${token})`;
66
+ previews.set(token, URL.createObjectURL(file));
67
+ const size = await sizeOf(file);
68
+ return formatImageLine({
69
+ indent: replacing?.indent ?? "",
70
+ alt: replacing?.alt ?? "",
71
+ url: token,
72
+ title: replacing?.title ?? "",
73
+ attrs: size ? withSize(replacing?.attrs || "{}", size.width, size.height) : replacing?.attrs ?? ""
74
+ });
75
+ }
76
+ /** Uploads one file and puts its URL in place of `token`, or undoes the placeholder. */
77
+ async function finish(view, file, token, options, previous) {
78
+ let settled = false;
79
+ const settle = () => {
80
+ if (!settled) options.onProgress(-1);
81
+ settled = true;
82
+ };
83
+ try {
84
+ const url = await options.upload(file);
85
+ settle();
86
+ const at = find(view, token);
87
+ if (at >= 0) view.dispatch({
88
+ changes: {
89
+ from: at,
90
+ to: at + token.length,
91
+ insert: url
92
+ },
93
+ userEvent: "input.upload"
94
+ });
95
+ } catch (error) {
96
+ settle();
97
+ const at = find(view, token);
98
+ if (at >= 0) {
99
+ const line = view.state.doc.lineAt(at);
100
+ const now = parseImageLine(line.text);
101
+ const changes = previous && now ? {
102
+ from: line.from,
103
+ to: line.to,
104
+ insert: formatImageLine({
105
+ ...now,
106
+ url: previous.url,
107
+ attrs: previous.attrs
108
+ })
109
+ } : {
110
+ from: line.from,
111
+ to: Math.min(line.to + 1, view.state.doc.length)
112
+ };
113
+ view.dispatch({
114
+ changes,
115
+ userEvent: "delete.upload"
116
+ });
117
+ }
118
+ options.onError(error, file);
119
+ } finally {
120
+ settle();
121
+ const local = previews.get(token);
122
+ previews.delete(token);
123
+ if (local) setTimeout(() => URL.revokeObjectURL(local), 3e4);
124
+ }
125
+ }
126
+ /**
127
+ * Uploads `files`, inserted at `at`, each on its own line, in one edit; or uploads the
128
+ * first into the image line `replace`. Placeholders go in at once and the uploads run
129
+ * side by side.
130
+ */
131
+ async function uploadFiles(view, files, options, target) {
132
+ const replace = "replace" in target ? target.replace : void 0;
133
+ const uploads = (replace ? files.slice(0, 1) : files).map((file) => ({
134
+ file,
135
+ token: nextToken()
136
+ }));
137
+ if (!uploads.length) return;
138
+ options.onProgress(uploads.length);
139
+ const current = replace ? parseImageLine(view.state.sliceDoc(replace.from, replace.to)) : null;
140
+ const previous = uploads[0]?.file.type.startsWith("image/") ? current : null;
141
+ const lines = await Promise.all(uploads.map(({ file, token }) => placeholderLine(file, token, previous)));
142
+ if (replace) view.dispatch({
143
+ changes: {
144
+ ...replace,
145
+ insert: lines[0]
146
+ },
147
+ userEvent: "input.upload"
148
+ });
149
+ else {
150
+ const { state } = view;
151
+ const at = Math.min("at" in target ? target.at : 0, state.doc.length);
152
+ const before = at > 0 && state.sliceDoc(at - 1, at) !== "\n" ? "\n" : "";
153
+ const after = state.sliceDoc(at, at + 1) === "\n" ? "" : "\n";
154
+ const insert = before + lines.join("\n") + after;
155
+ view.dispatch({
156
+ changes: {
157
+ from: at,
158
+ insert
159
+ },
160
+ selection: { anchor: at + insert.length },
161
+ userEvent: "input.upload"
162
+ });
163
+ }
164
+ await Promise.all(uploads.map(({ file, token }) => finish(view, file, token, options, previous)));
165
+ }
166
+ function element(tag, props = {}, ...children) {
167
+ const { dataPart, ...rest } = props;
168
+ const node = Object.assign(document.createElement(tag), rest);
169
+ if (dataPart) node.dataset.part = dataPart;
170
+ node.append(...children);
171
+ return node;
172
+ }
173
+ function pickFile(onFile) {
174
+ const input = element("input", {
175
+ type: "file",
176
+ accept: "image/*"
177
+ });
178
+ input.addEventListener("change", () => {
179
+ const file = input.files?.[0];
180
+ if (file) onFile(file);
181
+ });
182
+ input.click();
183
+ }
184
+ const parts = /* @__PURE__ */ new WeakMap();
185
+ var ImageCardWidget = class extends WidgetType {
186
+ source;
187
+ selected;
188
+ options;
189
+ constructor(source, selected, options) {
190
+ super();
191
+ this.source = source;
192
+ this.selected = selected;
193
+ this.options = options;
194
+ }
195
+ eq(other) {
196
+ return other.source === this.source && other.selected === this.selected;
197
+ }
198
+ /** The image line this card stands for, wherever it is now. */
199
+ range(view, dom) {
200
+ const line = view.state.doc.lineAt(view.posAtDOM(dom));
201
+ return {
202
+ from: line.from,
203
+ to: line.to
204
+ };
205
+ }
206
+ edit(view, dom, change) {
207
+ const range = this.range(view, dom);
208
+ const current = parseImageLine(view.state.sliceDoc(range.from, range.to));
209
+ if (!current || view.state.readOnly) return;
210
+ view.dispatch({
211
+ changes: {
212
+ ...range,
213
+ insert: formatImageLine({
214
+ ...current,
215
+ ...change
216
+ })
217
+ },
218
+ userEvent: "input.image"
219
+ });
220
+ }
221
+ /** Back to writing, on the line after the image. */
222
+ leave(view, dom) {
223
+ const { to } = this.range(view, dom);
224
+ if (to === view.state.doc.length) view.dispatch({
225
+ changes: {
226
+ from: to,
227
+ insert: "\n"
228
+ },
229
+ selection: { anchor: to + 1 }
230
+ });
231
+ else view.dispatch({ selection: { anchor: to + 1 } });
232
+ view.focus();
233
+ }
234
+ toDOM(view) {
235
+ const t = this.options.translations;
236
+ const upload = this.options.uploadInto;
237
+ const image = element("img", { alt: "" });
238
+ const choose = element("button", {
239
+ type: "button",
240
+ textContent: t.imageChoose
241
+ });
242
+ const url = element("input", {
243
+ type: "url",
244
+ placeholder: t.imageUrl
245
+ });
246
+ url.setAttribute("aria-label", t.imageUrl);
247
+ const empty = element("div", { className: "cm-md-image-empty" }, ...upload ? [element("span", { textContent: t.imageDrop }), choose] : [url]);
248
+ const status = element("div", {
249
+ className: "cm-md-image-status",
250
+ textContent: t.imageUploading
251
+ });
252
+ status.setAttribute("role", "status");
253
+ const replace = element("button", {
254
+ type: "button",
255
+ textContent: t.imageReplace
256
+ });
257
+ const remove = element("button", {
258
+ type: "button",
259
+ textContent: t.imageRemove
260
+ });
261
+ const frame = element("div", { className: "cm-md-image-frame" }, image, empty, status, element("div", { className: "cm-md-image-actions" }, ...upload ? [replace] : [], remove));
262
+ const caption = element("input", {
263
+ type: "text",
264
+ placeholder: t.imageCaption,
265
+ className: "cm-md-image-caption"
266
+ });
267
+ caption.setAttribute("aria-label", t.imageCaption);
268
+ const alt = element("input", {
269
+ type: "text",
270
+ placeholder: t.imageAltHint
271
+ });
272
+ const altField = element("label", { className: "cm-md-image-alt" }, element("span", { textContent: t.imageAlt }), alt);
273
+ const root = element("div", {
274
+ className: "cm-md-image",
275
+ dataPart: "writer-image"
276
+ }, element("div", { dataPart: "writer-content" }, element("figure", {}, frame, element("figcaption", {}, caption), altField)));
277
+ caption.addEventListener("input", () => this.edit(view, root, { title: caption.value }));
278
+ alt.addEventListener("input", () => this.edit(view, root, { alt: alt.value }));
279
+ url.addEventListener("change", () => this.edit(view, root, { url: url.value.trim() }));
280
+ for (const input of [
281
+ caption,
282
+ alt,
283
+ url
284
+ ]) input.addEventListener("keydown", (event) => {
285
+ if (event.key === "Enter" || event.key === "Escape") {
286
+ event.preventDefault();
287
+ this.leave(view, root);
288
+ }
289
+ });
290
+ if (upload) {
291
+ const choosePicked = () => pickFile((file) => upload(view, file, this.range(view, root)));
292
+ choose.addEventListener("click", choosePicked);
293
+ replace.addEventListener("click", choosePicked);
294
+ frame.addEventListener("dragover", (event) => {
295
+ if (!event.dataTransfer?.types.includes("Files")) return;
296
+ event.preventDefault();
297
+ frame.dataset.dropping = "";
298
+ });
299
+ frame.addEventListener("dragleave", () => delete frame.dataset.dropping);
300
+ frame.addEventListener("drop", (event) => {
301
+ const file = event.dataTransfer?.files[0];
302
+ delete frame.dataset.dropping;
303
+ if (!file?.type.startsWith("image/")) return;
304
+ event.preventDefault();
305
+ event.stopPropagation();
306
+ upload(view, file, this.range(view, root));
307
+ });
308
+ }
309
+ remove.addEventListener("click", () => {
310
+ const { from, to } = this.range(view, root);
311
+ view.dispatch({
312
+ changes: {
313
+ from,
314
+ to: Math.min(to + 1, view.state.doc.length)
315
+ },
316
+ selection: { anchor: from },
317
+ userEvent: "delete.image"
318
+ });
319
+ view.focus();
320
+ });
321
+ image.addEventListener("mousedown", (event) => {
322
+ event.preventDefault();
323
+ const { from, to } = this.range(view, root);
324
+ view.dispatch({ selection: {
325
+ anchor: from,
326
+ head: to
327
+ } });
328
+ view.focus();
329
+ });
330
+ parts.set(root, {
331
+ root,
332
+ frame,
333
+ image,
334
+ empty,
335
+ status,
336
+ caption,
337
+ alt
338
+ });
339
+ this.update(root);
340
+ return root;
341
+ }
342
+ updateDOM(dom) {
343
+ if (!parts.has(dom)) return false;
344
+ this.update(dom);
345
+ return true;
346
+ }
347
+ update(dom) {
348
+ const card = parts.get(dom);
349
+ const line = parseImageLine(this.source);
350
+ if (!card || !line) return;
351
+ const { width, height } = imageSize(line.attrs);
352
+ const local = previews.get(line.url);
353
+ const src = local ?? (isUploadPlaceholder(line.url) ? "" : line.url);
354
+ card.root.toggleAttribute("data-selected", this.selected);
355
+ card.frame.toggleAttribute("data-empty", !src);
356
+ card.frame.toggleAttribute("data-uploading", !!local);
357
+ card.frame.style.aspectRatio = width && height ? `${width} / ${height}` : "";
358
+ card.image.hidden = !src;
359
+ if (width && height) {
360
+ card.image.width = width;
361
+ card.image.height = height;
362
+ } else {
363
+ card.image.removeAttribute("width");
364
+ card.image.removeAttribute("height");
365
+ }
366
+ card.image.alt = line.alt;
367
+ if (src && card.wanted !== src) {
368
+ card.wanted = src;
369
+ const next = new Image();
370
+ const show = () => {
371
+ if (card.wanted === src) card.image.setAttribute("src", src);
372
+ };
373
+ next.addEventListener("load", show);
374
+ next.addEventListener("error", show);
375
+ next.src = src;
376
+ if (!card.image.getAttribute("src")) card.image.setAttribute("src", src);
377
+ } else if (!src) {
378
+ card.wanted = void 0;
379
+ card.image.removeAttribute("src");
380
+ }
381
+ if (document.activeElement !== card.caption) card.caption.value = line.title;
382
+ if (document.activeElement !== card.alt) card.alt.value = line.alt;
383
+ }
384
+ ignoreEvent() {
385
+ return true;
386
+ }
387
+ };
388
+ export { ImageCardWidget, formatImageLine, imageSize, parseImageLine, uploadFiles };
@@ -0,0 +1,2 @@
1
+ import "./images.js";
2
+ import { Extension, StateField } from "@codemirror/state";