@14ch/svelte-md-outliner 0.0.2 → 0.0.3

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/CHANGELOG.md CHANGED
@@ -5,6 +5,37 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.0.3] - 2026-09-02
9
+
10
+ ### Added
11
+
12
+ - Images are drawn as images. `![alt](src)`, `![alt](src "title")` and the
13
+ reference form are read as image nodes and written back as image notation.
14
+ They go anywhere text goes, including headings and table cells, and typing the
15
+ notation converts it as you close the bracket.
16
+ - `uploadImage` prop: paste an image and you are handed the raw `File`; the URL
17
+ you return is inserted at the paste position. Storage, formats, size limits and
18
+ sanitizing are yours. Reject or resolve with `null` to decline — the document
19
+ is not touched until you answer, and declining leaves it as it was.
20
+ - CSS custom properties for images: `--markdown-editor-image-max-height`,
21
+ `--markdown-editor-image-status-background`,
22
+ `--markdown-editor-image-status-text`.
23
+
24
+ ### Changed
25
+
26
+ - `EditorMessages` has two new required entries, `imageUploading` and
27
+ `imageLoadError`. Breaking if you supply a whole language set; partial
28
+ overrides are unaffected.
29
+ - Saved `viewState` entries for headings containing an image are discarded on
30
+ load, since a heading's text now spells an image as its alt text.
31
+
32
+ ### Fixed
33
+
34
+ - Image notation no longer breaks when you save. `![alt](img.png)` used to come
35
+ back as `!\[alt\](img.png)` and never recover.
36
+ - Images copied from a browser are no longer silently dropped. Without
37
+ `uploadImage` they keep pointing at their original URL.
38
+
8
39
  ## [0.0.2] - 2026-09-01
9
40
 
10
41
  ### Added
package/README.ja.md CHANGED
@@ -51,25 +51,41 @@ import '@14ch/svelte-md-outliner/styles/editor.css';
51
51
  <MarkdownEditor bind:value bind:viewState label="議事録" maxWidth="42rem" />
52
52
  ```
53
53
 
54
- | | 型 | 既定 | |
55
- | ------------------- | -------------------------------- | ---------- | ------------------------------------------------------ |
56
- | `value` | `string` | `''` | 本文のマークダウン(`bind:` 可) |
57
- | `onChange` | `(markdown: string) => void` | — | `bind:value` を使うなら不要 |
58
- | `viewState` | `ViewState` | — | どの見出しを畳んでいるか、どこをフォーカスしているか |
59
- | `onViewStateChange` | `(viewState: ViewState) => void` | — | `bind:viewState` を使うなら不要 |
60
- | `label` | `string` | 内蔵の文言 | 編集エリアのアクセシブルネーム |
61
- | `readonly` | `boolean` | `false` | 入力・編集コマンド・貼り付けを受け付けない |
62
- | `autofocus` | `boolean` | `false` | マウント時にフォーカスする |
63
- | `class` | `string` | `''` | 追加のクラス名 |
64
- | `padding` | `string` | トークン | CSS の `padding` と同じ書き方 |
65
- | `maxWidth` | `string` | トークン | 行の長さ。**クリックできる範囲は元の幅のまま** |
66
- | `lang` | `'en' \| 'ja'` | `'en'` | 同梱の言語 |
67
- | `messages` | `EditorMessagesOverride` | — | 文字列の差し替え。同梱しない言語は一式を渡す |
68
- | `shortcutHelp` | `boolean` | `true` | 組み込みのショートカット一覧(`Mod-Alt-/`) |
69
- | `contextMenu` | `boolean` | `true` | 組み込みのコンテキストメニュー(右クリック / `Mod-/`) |
54
+ | | 型 | 既定 | |
55
+ | ------------------- | ----------------------------------------- | ---------- | ------------------------------------------------------ |
56
+ | `value` | `string` | `''` | 本文のマークダウン(`bind:` 可) |
57
+ | `onChange` | `(markdown: string) => void` | — | `bind:value` を使うなら不要 |
58
+ | `viewState` | `ViewState` | — | どの見出しを畳んでいるか、どこをフォーカスしているか |
59
+ | `onViewStateChange` | `(viewState: ViewState) => void` | — | `bind:viewState` を使うなら不要 |
60
+ | `label` | `string` | 内蔵の文言 | 編集エリアのアクセシブルネーム |
61
+ | `readonly` | `boolean` | `false` | 入力・編集コマンド・貼り付けを受け付けない |
62
+ | `autofocus` | `boolean` | `false` | マウント時にフォーカスする |
63
+ | `class` | `string` | `''` | 追加のクラス名 |
64
+ | `padding` | `string` | トークン | CSS の `padding` と同じ書き方 |
65
+ | `maxWidth` | `string` | トークン | 行の長さ。**クリックできる範囲は元の幅のまま** |
66
+ | `lang` | `'en' \| 'ja'` | `'en'` | 同梱の言語 |
67
+ | `messages` | `EditorMessagesOverride` | — | 文字列の差し替え。同梱しない言語は一式を渡す |
68
+ | `shortcutHelp` | `boolean` | `true` | 組み込みのショートカット一覧(`Mod-Alt-/`) |
69
+ | `contextMenu` | `boolean` | `true` | 組み込みのコンテキストメニュー(右クリック / `Mod-/`) |
70
+ | `uploadImage` | `(file: File) => Promise<string \| null>` | — | 貼り付けられた画像を引き受け、表示に使う URL を返す |
70
71
 
71
72
  `viewState` は**今どう見ているか**であって、文書の内容ではない。このモジュールは何も保存しないので、保存先は利用側が決める(保存しなくてもよい)。
72
73
 
74
+ ### 画像
75
+
76
+ `![alt](src)` は実際の画像として描かれる。画像を貼り付けると `uploadImage` が生の `File` を受け取り、返した URL が画像記法として貼り付け位置へ入る。どこへ保存するか、どの形式と大きさを受け入れるか、中身をどう無害化するか(SVG など)は**すべて利用側の裁量**である。モジュールが見るのは「クリップボードに画像ファイルがあるか」だけで、保存は一切持たない。
77
+
78
+ ```ts
79
+ const uploadImage = async (file: File) => {
80
+ const url = await myStorage.put(file); // 断るときは null を返す
81
+ return url;
82
+ };
83
+ ```
84
+
85
+ 待っているあいだは貼り付け位置に印が出るだけで、**文書は 1 文字も変わらない**。失敗すれば印が消え、貼り付けが無かった状態のまま残る。`uploadImage` を渡さなければ従来の貼り付けが働き、読み取り専用のあいだは呼ばれない。
86
+
87
+ **画像を描くと、その先へ取りに行く。** 外部の URL が書かれた文書は、表示のたびにその先へ取得が飛ぶ(記法を描く以上避けられない)。
88
+
73
89
  同梱していない言語は、同梱の一式を土台にする。
74
90
 
75
91
  ```ts
package/README.md CHANGED
@@ -51,25 +51,41 @@ import '@14ch/svelte-md-outliner/styles/editor.css';
51
51
  <MarkdownEditor bind:value bind:viewState label="Meeting notes" maxWidth="42rem" />
52
52
  ```
53
53
 
54
- | | Type | Default | |
55
- | ------------------- | -------------------------------- | -------- | ----------------------------------------------------------- |
56
- | `value` | `string` | `''` | Markdown source (bindable) |
57
- | `onChange` | `(markdown: string) => void` | — | Not needed when you use `bind:value` |
58
- | `viewState` | `ViewState` | — | Which headings are folded, which section is zoomed |
59
- | `onViewStateChange` | `(viewState: ViewState) => void` | — | Not needed when you use `bind:viewState` |
60
- | `label` | `string` | built-in | Accessible name for the editing surface |
61
- | `readonly` | `boolean` | `false` | Rejects typing, commands and pastes |
62
- | `autofocus` | `boolean` | `false` | Focus on mount |
63
- | `class` | `string` | `''` | Extra class names |
64
- | `padding` | `string` | token | Written exactly like CSS `padding` |
65
- | `maxWidth` | `string` | token | Line length. **The clickable surface keeps the full width** |
66
- | `lang` | `'en' \| 'ja'` | `'en'` | Bundled UI language |
67
- | `messages` | `EditorMessagesOverride` | — | Replace individual strings, or supply a whole language |
68
- | `shortcutHelp` | `boolean` | `true` | Built-in shortcut sheet (`Mod-Alt-/`) |
69
- | `contextMenu` | `boolean` | `true` | Built-in context menu (right click / `Mod-/`) |
54
+ | | Type | Default | |
55
+ | ------------------- | ----------------------------------------- | -------- | ----------------------------------------------------------- |
56
+ | `value` | `string` | `''` | Markdown source (bindable) |
57
+ | `onChange` | `(markdown: string) => void` | — | Not needed when you use `bind:value` |
58
+ | `viewState` | `ViewState` | — | Which headings are folded, which section is zoomed |
59
+ | `onViewStateChange` | `(viewState: ViewState) => void` | — | Not needed when you use `bind:viewState` |
60
+ | `label` | `string` | built-in | Accessible name for the editing surface |
61
+ | `readonly` | `boolean` | `false` | Rejects typing, commands and pastes |
62
+ | `autofocus` | `boolean` | `false` | Focus on mount |
63
+ | `class` | `string` | `''` | Extra class names |
64
+ | `padding` | `string` | token | Written exactly like CSS `padding` |
65
+ | `maxWidth` | `string` | token | Line length. **The clickable surface keeps the full width** |
66
+ | `lang` | `'en' \| 'ja'` | `'en'` | Bundled UI language |
67
+ | `messages` | `EditorMessagesOverride` | — | Replace individual strings, or supply a whole language |
68
+ | `shortcutHelp` | `boolean` | `true` | Built-in shortcut sheet (`Mod-Alt-/`) |
69
+ | `contextMenu` | `boolean` | `true` | Built-in context menu (right click / `Mod-/`) |
70
+ | `uploadImage` | `(file: File) => Promise<string \| null>` | — | Takes a pasted image, returns the URL to display |
70
71
 
71
72
  `viewState` is **how you are looking at the document**, not its content. This module stores nothing, so persist it wherever you like — or not at all.
72
73
 
74
+ ### Images
75
+
76
+ `![alt](src)` is rendered as a real image. Paste an image and `uploadImage` receives the raw `File`; the URL you return is inserted as image notation at the paste position. Where the bytes go, which formats and sizes you accept, and how you sanitize them (SVG, for instance) are all yours — this module only checks whether the clipboard holds an image file, and never stores anything itself.
77
+
78
+ ```ts
79
+ const uploadImage = async (file: File) => {
80
+ const url = await myStorage.put(file); // or return null to reject the paste
81
+ return url;
82
+ };
83
+ ```
84
+
85
+ While it waits, a marker is shown at the paste position and **the document is not touched**; a failure removes the marker and leaves the document exactly as it was. Without `uploadImage` the paste falls through to the ordinary one. Pastes are ignored entirely while `readonly`.
86
+
87
+ **Rendering an image fetches it.** A document that names an external URL will request it from that host every time it is shown — that is what drawing image notation means.
88
+
73
89
  For a language that is not bundled, start from a bundled set:
74
90
 
75
91
  ```ts
@@ -133,6 +133,11 @@
133
133
  --markdown-editor-breadcrumb-separator: '>';
134
134
  --markdown-editor-front-matter-padding: 0.4em 0.8em;
135
135
  --markdown-editor-mermaid-min-height: 2.5em;
136
+ /**
137
+ * 画像の高さの上限。**縦に長い画像 1 枚で画面が埋まらないようにする。**
138
+ * 横は本文の幅を超えない(`max-width: 100%`)ので、上限を持つのは高さだけでよい。
139
+ */
140
+ --markdown-editor-image-max-height: 20em;
136
141
  }
137
142
 
138
143
  /**
@@ -1054,6 +1059,54 @@
1054
1059
 
1055
1060
  /* --- インライン --- */
1056
1061
 
1062
+ /**
1063
+ * 画像。**版面を崩さない**(要件 2.4)——本文の幅を超えず、縦に長い 1 枚で画面を埋めない。
1064
+ *
1065
+ * 包む要素を置くのは、画像の隣に状態の一行を出すためである(画像そのものは replaced 要素
1066
+ * なので、擬似要素を持てない)。素の描き出し(スキーマの `toDOM`)は包む要素を持たず、
1067
+ * `img` が直に `markdown-editor__image-preview` を名乗る。
1068
+ */
1069
+ .markdown-editor__image {
1070
+ display: inline-block;
1071
+ max-width: 100%;
1072
+ /* 行の下端にそろえる(既定の baseline だと、行の下に文字の下ぶんの隙間ができる) */
1073
+ vertical-align: bottom;
1074
+ }
1075
+
1076
+ .markdown-editor__image-preview {
1077
+ display: block;
1078
+ max-width: 100%;
1079
+ max-height: var(--markdown-editor-image-max-height);
1080
+ /* 上限で片方が縮んだときも、縦横の比を保つ */
1081
+ object-fit: contain;
1082
+ }
1083
+
1084
+ /* 読み込めなかった画像の枠(実行環境が出す壊れた画像の印)は出さない。一行で伝える */
1085
+ .markdown-editor__image--failed .markdown-editor__image-preview {
1086
+ display: none;
1087
+ }
1088
+
1089
+ /**
1090
+ * 引き受けを待っているあいだの印と、読み込みに失敗したことの一行。
1091
+ * **地の文と区別できる控えめな面で示す**(Mermaid の状態表示と同じ作法)。
1092
+ *
1093
+ * 印(`--placeholder`)は文書に何も入れずに置かれる目印であり、書き出しには現れない
1094
+ * (→ `imagePaste.ts`)。見た目は失敗の一行と同じもので足りる。
1095
+ */
1096
+ .markdown-editor__image-status,
1097
+ .markdown-editor__image-placeholder {
1098
+ display: inline-block;
1099
+ padding: 0.15em 0.5em;
1100
+ background: var(--markdown-editor-image-status-background);
1101
+ color: var(--markdown-editor-image-status-text);
1102
+ font-size: var(--markdown-editor-font-size-sm);
1103
+ }
1104
+
1105
+ /* 読み込めた画像では、状態の一行は場所を取らない */
1106
+ .markdown-editor__image-status:empty {
1107
+ display: none;
1108
+ }
1109
+
1057
1110
  /**
1058
1111
  * 脚注のマーカー(`[^1]`)。**上付きの小さなマーカーとして描くだけ**で、注へ飛ぶ仕掛けは持たない
1059
1112
  * (→ `docs/backlog.md` C13)。文字そのものは記法の原文のままなので、選んで消せば
@@ -304,6 +304,10 @@
304
304
  /* 中身が空のときに出すブロックの名前。ファイルには無い文字列なので、値より薄く出す */
305
305
  --markdown-editor-front-matter-label: var(--markdown-editor-text-subtle);
306
306
 
307
+ /* 引き受けを待っているあいだ・画像を出せなかったときに出す一行 */
308
+ --markdown-editor-image-status-background: var(--markdown-editor-surface-accent);
309
+ --markdown-editor-image-status-text: var(--markdown-editor-text-subtle);
310
+
307
311
  /* Mermaid ブロックの図の表示領域 */
308
312
  --markdown-editor-mermaid-background: var(--markdown-editor-surface-accent);
309
313
  /* 図を描けないあいだ・描けなかったときに出す一行 */
@@ -1,5 +1,6 @@
1
1
  <script lang="ts" module>
2
2
  import type { EditorLang, EditorMessagesOverride } from '../messages/messages.types';
3
+ import type { ImageUpload } from '../operations/plugins/imagePaste';
3
4
  import type {
4
5
  FrontMatterFields,
5
6
  FrontMatterWriteError,
@@ -74,6 +75,20 @@
74
75
  * 使わない設定では、右クリックに対して実行環境の既定のメニューを妨げない。
75
76
  */
76
77
  contextMenu?: boolean;
78
+ /**
79
+ * 貼り付けられた画像を引き受け、**表示に使う URL を返す**。
80
+ *
81
+ * 保存先・形式やサイズの判定・内容の無害化・アクセス制御は、すべて呼び出し側の
82
+ * 裁量である。モジュールが見るのは「クリップボードに画像ファイルがあるか」だけで、
83
+ * 受け取った `File` は加工せずそのまま渡す。
84
+ *
85
+ * 失敗は reject するか `null` で解決する。どちらでも、待っているあいだの表示が
86
+ * 消えて**文書は貼り付けが無かったまま**になる。
87
+ *
88
+ * 渡さなければ、画像の貼り付けに対して何もしない(従来どおりの貼り付けが働く)。
89
+ * 読み取り専用のあいだは呼ばれない。
90
+ */
91
+ uploadImage?: ImageUpload;
77
92
  }
78
93
 
79
94
  /** `padding` を四辺へ展開したもの。CSS 側へは辺ごとに渡す(→ `expandPadding`) */
@@ -170,7 +185,8 @@
170
185
  viewState = $bindable(),
171
186
  onViewStateChange,
172
187
  shortcutHelp = true,
173
- contextMenu = true
188
+ contextMenu = true,
189
+ uploadImage
174
190
  }: MarkdownEditorProps = $props();
175
191
 
176
192
  // --- 状態 ---
@@ -189,12 +205,14 @@
189
205
  loadError: text.mermaidLoadError
190
206
  });
191
207
  const frontMatterText = $derived(text.frontMatterLabel);
208
+ const imageText = $derived({ uploading: text.imageUploading, loadError: text.imageLoadError });
192
209
  const presentation = $derived({
193
210
  readonly,
194
211
  label: accessibleName,
195
212
  lang,
196
213
  mermaidText,
197
- frontMatterText
214
+ frontMatterText,
215
+ imageText
198
216
  });
199
217
 
200
218
  // --- 1 度だけ組み立てるもの ---
@@ -232,6 +250,12 @@
232
250
  lang: untrack(() => lang),
233
251
  mermaidText: untrack(() => mermaidText),
234
252
  frontMatterText: untrack(() => frontMatterText),
253
+ imageText: untrack(() => imageText),
254
+ /**
255
+ * 引き受け先は**値ではなく「呼ぶ時点で読む形」で渡す。** prop が後から変わっても
256
+ * 呼ぶ時点の値が使われ、表示の組み直し(`view.setProps`)も起きない。
257
+ */
258
+ imageUpload: () => uploadImage,
235
259
  extensions: [controller.extension, menuController.extension]
236
260
  };
237
261
 
@@ -1,4 +1,5 @@
1
1
  import type { EditorLang, EditorMessagesOverride } from '../messages/messages.types';
2
+ import type { ImageUpload } from '../operations/plugins/imagePaste';
2
3
  import type { FrontMatterFields, FrontMatterWriteError, FrontMatterWriteOutcome, MarkdownParseError } from '../models/markdown/markdown.types';
3
4
  import type { Result } from '../utils/result.types';
4
5
  import type { ViewState } from '../models/viewState/viewState.types';
@@ -67,6 +68,20 @@ export interface MarkdownEditorProps {
67
68
  * 使わない設定では、右クリックに対して実行環境の既定のメニューを妨げない。
68
69
  */
69
70
  contextMenu?: boolean;
71
+ /**
72
+ * 貼り付けられた画像を引き受け、**表示に使う URL を返す**。
73
+ *
74
+ * 保存先・形式やサイズの判定・内容の無害化・アクセス制御は、すべて呼び出し側の
75
+ * 裁量である。モジュールが見るのは「クリップボードに画像ファイルがあるか」だけで、
76
+ * 受け取った `File` は加工せずそのまま渡す。
77
+ *
78
+ * 失敗は reject するか `null` で解決する。どちらでも、待っているあいだの表示が
79
+ * 消えて**文書は貼り付けが無かったまま**になる。
80
+ *
81
+ * 渡さなければ、画像の貼り付けに対して何もしない(従来どおりの貼り付けが働く)。
82
+ * 読み取り専用のあいだは呼ばれない。
83
+ */
84
+ uploadImage?: ImageUpload;
70
85
  }
71
86
  /** `padding` を四辺へ展開したもの。CSS 側へは辺ごとに渡す(→ `expandPadding`) */
72
87
  export interface EditorPadding {
package/dist/index.d.ts CHANGED
@@ -8,6 +8,11 @@ export { default as MarkdownEditor } from './components/MarkdownEditor.svelte';
8
8
  export type { MarkdownEditorProps, MarkdownEditorApi } from './components/MarkdownEditor.svelte';
9
9
  export { en, ja } from './messages';
10
10
  export type { EditorMessages, EditorMessagesOverride, EditorLang, EditorShortcutCategory } from './messages/messages.types';
11
+ /**
12
+ * 貼り付けられた画像の引き受け先の型(`MarkdownEditor` の `uploadImage` に渡す)。
13
+ * `File` を受け取り、表示に使う URL を返す。失敗は reject か `null` で表す。
14
+ */
15
+ export type { ImageUpload } from './operations/plugins/imagePaste';
11
16
  export type { ViewState, ViewSectionRef } from './models/viewState/viewState.types';
12
17
  /**
13
18
  * マークダウン文字列を、エディタを置かずに読み書きするための純関数。
@@ -9,6 +9,8 @@ export const en = {
9
9
  mermaidLoading: 'Loading diagram renderer…',
10
10
  mermaidRenderError: 'This source cannot be rendered as a diagram',
11
11
  mermaidLoadError: 'Failed to load the diagram renderer',
12
+ imageUploading: 'Uploading image…',
13
+ imageLoadError: 'Failed to load the image',
12
14
  frontMatterLabel: 'Front Matter',
13
15
  shortcutCategories: {
14
16
  edit: 'Edit',
@@ -26,6 +26,8 @@ export function resolveMessages(lang = DEFAULT_LANG, overrides) {
26
26
  mermaidLoading: overrides.mermaidLoading ?? base.mermaidLoading,
27
27
  mermaidRenderError: overrides.mermaidRenderError ?? base.mermaidRenderError,
28
28
  mermaidLoadError: overrides.mermaidLoadError ?? base.mermaidLoadError,
29
+ imageUploading: overrides.imageUploading ?? base.imageUploading,
30
+ imageLoadError: overrides.imageLoadError ?? base.imageLoadError,
29
31
  frontMatterLabel: overrides.frontMatterLabel ?? base.frontMatterLabel
30
32
  };
31
33
  }
@@ -9,6 +9,8 @@ export const ja = {
9
9
  mermaidLoading: '図の描画機能を読み込んでいます…',
10
10
  mermaidRenderError: 'この内容では図を描画できません',
11
11
  mermaidLoadError: '図の描画機能を読み込めませんでした',
12
+ imageUploading: '画像を読み込んでいます…',
13
+ imageLoadError: '画像を表示できませんでした',
12
14
  frontMatterLabel: 'Front Matter',
13
15
  shortcutCategories: {
14
16
  // グループは利用者の意図で分ける。「ブロックの操作」のような総称は使わない
@@ -32,6 +32,10 @@ export interface EditorMessages {
32
32
  readonly mermaidRenderError: string;
33
33
  /** 描画ライブラリの読み込みに失敗したことを伝える表示 */
34
34
  readonly mermaidLoadError: string;
35
+ /** 貼り付けた画像の引き受けを待っているあいだの表示 */
36
+ readonly imageUploading: string;
37
+ /** 画像の読み込みに失敗したことを伝える表示 */
38
+ readonly imageLoadError: string;
35
39
  /**
36
40
  * フロントマターにタイトルが無いときに、その場所へ薄く出す名前。
37
41
  * 状態の説明(「未設定です」)ではなく、**そこが何であるか**の表示である
@@ -55,5 +59,7 @@ export interface EditorMessagesOverride {
55
59
  readonly mermaidLoading?: string;
56
60
  readonly mermaidRenderError?: string;
57
61
  readonly mermaidLoadError?: string;
62
+ readonly imageUploading?: string;
63
+ readonly imageLoadError?: string;
58
64
  readonly frontMatterLabel?: string;
59
65
  }
@@ -7,6 +7,13 @@ export declare function isHeadingLevel(value: unknown): value is HeadingLevel;
7
7
  export interface HeadingAttrs {
8
8
  readonly level: HeadingLevel;
9
9
  }
10
+ /** 画像の属性。**記法に書かれているものだけ**を持つ(→ スキーマの `image`) */
11
+ export interface ImageAttributes {
12
+ readonly src: string;
13
+ readonly alt: string;
14
+ /** 記法にタイトルが無ければ null */
15
+ readonly title: string | null;
16
+ }
10
17
  /** 原文のまま保持する記法(HTML ブロックなど)を格納する */
11
18
  export interface UnknownBlockAttrs {
12
19
  readonly source: string;
@@ -158,14 +158,18 @@ const blockNodes = {
158
158
  /**
159
159
  * `block` グループに入れない。見出しは section の先頭にしか置けない。
160
160
  *
161
- * 中身を `text*` に絞るのは、**見出しに段落内改行を置かせない**ためである。
161
+ * 中身を `(text | image)*` に絞るのは、**見出しに段落内改行を置かせない**ためである。
162
162
  * ATX 見出し(`# ...`)はマークダウンでは 1 行のブロックで、行末の空白 2 つも `\` も
163
163
  * 改行にならない。書ける手段は生の `<br>` だけだが、見出しの文字列はパンくず・
164
164
  * 折りたたみの見出しとしても出る**1 行のもの**であり、改行を入れる場所ではない。
165
165
  * 解釈せず文字として残すため、書けば往復で `<br>` という文字列のまま残る(→ `hard_break`)。
166
+ *
167
+ * **画像は受ける。** 絞っている目的は改行を置かせないことであって、記法を持つ内容を
168
+ * 拒むことではない(`inline*` にすると `hard_break` まで通ってしまう)。読める 1 行の
169
+ * 文字は `headingText` が決める(画像は代替文字で表す)。
166
170
  */
167
171
  heading: {
168
- content: 'text*',
172
+ content: '(text | image)*',
169
173
  defining: true,
170
174
  attrs: { level: { default: MIN_HEADING_LEVEL } },
171
175
  toDOM: (node) => [
@@ -194,14 +198,14 @@ const blockNodes = {
194
198
  * `level` は**原文のレベル**をそのまま持つ。`heading` と違い構造上の深さから
195
199
  * 決め直さないのは、加わる階層が無く決め直す相手がいないためである。
196
200
  *
197
- * 中身を `text*` に絞る理由は `heading` と同じ(マークダウンでは 1 行のブロックで、
198
- * 改行を書く手段が無い)。
201
+ * 中身を `(text | image)*` に絞る理由は `heading` と同じ(マークダウンでは 1 行の
202
+ * ブロックで、改行を書く手段が無い)。画像を受けるところも同じである。
199
203
  *
200
204
  * parseDOM の規則の競合は並び順(スキーマのノード順)で決まり、`heading` の汎用
201
205
  * `h1`〜`h6` 規則が先に並ぶため、`priority` を上げて先に評価させる。
202
206
  */
203
207
  nested_heading: {
204
- content: 'text*',
208
+ content: '(text | image)*',
205
209
  group: 'block',
206
210
  defining: true,
207
211
  attrs: { level: { default: MIN_HEADING_LEVEL } },
@@ -331,6 +335,47 @@ const blockNodes = {
331
335
  toDOM: () => ['br'],
332
336
  parseDOM: [{ tag: 'br' }]
333
337
  },
338
+ /**
339
+ * 画像。**独立したインラインノード**であり、受け皿の文字ではない。
340
+ *
341
+ * 属性は**記法に書かれている 3 つ**だけを持つ。寸法・配置・読み込み状態は文書に
342
+ * 書かれていないものであり、属性にしない(読み込み状態は NodeView が持つ)。
343
+ *
344
+ * 中身を持たない葉として定義する。編集基盤は葉を atom として扱うため、選択・削除は
345
+ * 1 文字と同じ単位になる。置ける場所は**インラインを受ける場所すべて**で、記法を
346
+ * 解釈しない場所(コードブロック・Mermaid・フロントマター)は `text*` なので構造として
347
+ * 拒まれる。
348
+ *
349
+ * **`draggable` にしない。** ドラッグでの追加は対象外であり、半端な振る舞いを作らない。
350
+ *
351
+ * `toDOM` と `parseDOM` の両方が要る。**編集エリアの中でのコピー・貼り付けが DOM を
352
+ * 通る**ためである。`src` は空文字になりうる(`![alt]()` と書かれた文書)。空でも
353
+ * 読み込みに失敗した表示として扱い、ノードは落とさない。
354
+ */
355
+ image: {
356
+ inline: true,
357
+ group: 'inline',
358
+ attrs: { src: { default: '' }, alt: { default: '' }, title: { default: null } },
359
+ toDOM: (node) => [
360
+ 'img',
361
+ {
362
+ class: 'markdown-editor__image',
363
+ src: node.attrs.src,
364
+ alt: node.attrs.alt,
365
+ title: node.attrs.title
366
+ }
367
+ ],
368
+ parseDOM: [
369
+ {
370
+ tag: 'img[src]',
371
+ getAttrs: (element) => ({
372
+ src: element.getAttribute('src') ?? '',
373
+ alt: element.getAttribute('alt') ?? '',
374
+ title: element.getAttribute('title')
375
+ })
376
+ }
377
+ ]
378
+ },
334
379
  text: { group: 'inline' }
335
380
  };
336
381
  const tableNodeSpecs = tableNodes({
@@ -432,17 +477,20 @@ const marks = {
432
477
  },
433
478
  /**
434
479
  * その文字が**記法の原文**であり、書き出しで手を加えてはならないというマーク。
435
- * 文書モデルで表現できない記法(画像・インラインの HTML・番号付きの項目の
436
- * チェックボックス)は、このマークを付けた文字として取り込む。**ブロックの側の
480
+ * 文書モデルで表現できない記法(インラインの HTML・番号付きの項目のチェックボックス・
481
+ * 脚注のマーカー)は、このマークを付けた文字として取り込む。**ブロックの側の
437
482
  * `unknown_block` にあたるものが、インラインの側に無いことが壊れる理由だった。**
438
483
  *
484
+ * **画像はここに含まれない。** 画像は自分のノード(→ `image`)と自分の読み書きの
485
+ * 規則を持ち、正準な形で往復する。
486
+ *
439
487
  * **必ずマークの一覧のいちばん最後に置く。** マークの並びは宣言順(rank)の
440
488
  * 昇順で作られるため、最後に置いたものが最も内側になる。書き出しの
441
489
  * 「エスケープしない」(`escape: false`)が効くのは最も内側のマークのときだけであり、
442
490
  * **後ろへマークを足すと、エスケープしない性質が黙って失われる**。
443
491
  *
444
- * `excludes` を持たせないのは、リンクの中の画像・強調の中の画像で共存が要るため。
445
- * `inclusive: false` にするのは、**画像の直後に打った文字へマークが広がらない**ように
492
+ * `excludes` を持たせないのは、リンクの中・強調の中の記法で共存が要るため。
493
+ * `inclusive: false` にするのは、**記法の直後に打った文字へマークが広がらない**ように
446
494
  * するためである(広がると、書き手が普通に打った `[foo]` がエスケープされずリンクの
447
495
  * 一部として読み直されうる)。同じスキーマの `link` が既にこの形である。
448
496
  *
@@ -1,6 +1,15 @@
1
1
  import type { Node } from 'prosemirror-model';
2
2
  import type { Transaction } from 'prosemirror-state';
3
3
  import { type SectionPath, type SectionRef } from './document.types';
4
+ /**
5
+ * 見出しの**読める 1 行の文字**。パンくず・折りたたみの見出し・表示状態の突合キーは
6
+ * すべてこれを使う。
7
+ *
8
+ * **`textContent` を直に読まない。** あちらは葉ノードを飛ばすため、画像を含む見出しから
9
+ * 画像が黙って消える。ここでは代替文字を葉の文字表現として与え、読み手に見えているものと
10
+ * 同じ 1 行を返す。見出しには改行が入らないため(→ スキーマの `heading`)、区切りは要らない。
11
+ */
12
+ export declare function headingText(heading: Node): string;
4
13
  export interface SectionTree {
5
14
  /** 位置がもっとも内側で属するセクションを返す */
6
15
  resolveSection(doc: Node, pos: number): SectionRef | null;
@@ -2,6 +2,18 @@ import { MAX_HEADING_LEVEL } from './document.types';
2
2
  import { outlineSchema } from './schema';
3
3
  const SECTION = outlineSchema.nodes.section;
4
4
  const INTRO_SECTION = outlineSchema.nodes.intro_section;
5
+ const IMAGE = outlineSchema.nodes.image;
6
+ /**
7
+ * 見出しの**読める 1 行の文字**。パンくず・折りたたみの見出し・表示状態の突合キーは
8
+ * すべてこれを使う。
9
+ *
10
+ * **`textContent` を直に読まない。** あちらは葉ノードを飛ばすため、画像を含む見出しから
11
+ * 画像が黙って消える。ここでは代替文字を葉の文字表現として与え、読み手に見えているものと
12
+ * 同じ 1 行を返す。見出しには改行が入らないため(→ スキーマの `heading`)、区切りは要らない。
13
+ */
14
+ export function headingText(heading) {
15
+ return heading.textBetween(0, heading.content.size, '', (leaf) => leaf.type === IMAGE ? String(leaf.attrs.alt ?? '') : '');
16
+ }
5
17
  export const sectionTree = {
6
18
  resolveSection,
7
19
  resolveAncestors,
@@ -411,8 +411,17 @@ function parseInline(inline, into) {
411
411
  case 'link_close':
412
412
  marks = m.link.removeFromSet(marks);
413
413
  break;
414
+ /**
415
+ * 画像は独立したノードになる。直接の形・タイトルつき・参照の形を区別しない
416
+ * (行き先はトークンの属性に入っており、markdown-it が解決済みで渡す)。
417
+ * 代替文字の中の記法はトークンの側で文字へ落ちている。
418
+ */
414
419
  case 'image':
415
- pushVerbatim(imageNotation(token));
420
+ nodes.push(n.image.create({
421
+ src: token.attrGet('src') ?? '',
422
+ alt: token.content,
423
+ title: token.attrGet('title')
424
+ }, null, marks));
416
425
  break;
417
426
  // 印であることが画面から分かるように、見た目のマークだけ重ねる
418
427
  case 'footnote_ref':
@@ -484,22 +493,6 @@ function htmlElementContent(tokens, source) {
484
493
  });
485
494
  return inside;
486
495
  }
487
- /**
488
- * 画像の記法を、トークンの属性から組み立てる。
489
- *
490
- * **原文そのものは復元できない。** パーサが返すのは代替文字と属性だけで、
491
- * 記法の原文(`markup`)も位置(`map`)も持たない。したがって間隔・`<>`・引用符の
492
- * 種類は正準形へ揃う(`![alt]( <i.png> '題' )` → `![alt](i.png "題")`)。
493
- * **壊れているのは記法が文字になることであって、書き方ではない。**
494
- *
495
- * 参照の形(`![alt][ref]`)も同じ経路を通る。行き先が属性に入っているためである。
496
- */
497
- function imageNotation(token) {
498
- const src = token.attrGet('src') ?? '';
499
- const title = String(token.attrGet('title') ?? '');
500
- const suffix = title ? ` "${title.replace(/"/g, '\\"')}"` : '';
501
- return `![${token.content}](${src}${suffix})`;
502
- }
503
496
  // --- ヘルパー ---
504
497
  function matchingClose(tokens, start, openType, closeType) {
505
498
  let depth = 0;
@@ -216,6 +216,21 @@ const serializeHardBreak = (state, node, parent, index) => {
216
216
  }
217
217
  }
218
218
  };
219
+ /**
220
+ * 画像。**記法を組み立てる場所はここだけ**である(読み込みは属性を写すだけ → `parser.ts`)。
221
+ *
222
+ * 代替文字は**そのスロットの原文**なので、1 文字も足さず 1 文字も削らない。書き出しの
223
+ * 既定のエスケープへ回すと、原文にあった記号(`**` や `\[`)に `\` が重なり、
224
+ * **往復のたびに記号が増える**。逃がすのは、書いたものが別の意味に読み直される 2 つ——
225
+ * 出どころの丸括弧(`(` で閉じてしまう)と、タイトルの引用符(`"` で閉じてしまう)だけである。
226
+ */
227
+ const serializeImage = (state, node) => {
228
+ const alt = String(node.attrs.alt ?? '');
229
+ const src = String(node.attrs.src ?? '').replace(/[()]/g, '\\$&');
230
+ const title = node.attrs.title;
231
+ const suffix = title ? ` "${String(title).replace(/"/g, '\\"')}"` : '';
232
+ state.write(`![${alt}](${src}${suffix})`);
233
+ };
219
234
  /**
220
235
  * 文字。**改行の次の行だけは、行頭の記号を自分でエスケープする。**
221
236
  *
@@ -330,6 +345,7 @@ const blocks = {
330
345
  const nodes = {
331
346
  ...Object.fromEntries(Object.entries(blocks).map(([name, serialize]) => [name, afterBlankLine(serialize)])),
332
347
  hard_break: serializeHardBreak,
348
+ image: serializeImage,
333
349
  text: serializeText
334
350
  };
335
351
  const marks = {
@@ -364,15 +380,26 @@ const marks = {
364
380
  };
365
381
  const markdownSerializer = new MarkdownSerializer(nodes, marks);
366
382
  // --- ヘルパー ---
383
+ /**
384
+ * 中身が空行だけか(先頭セクションを書き出すかの判定)。
385
+ *
386
+ * **文字だけを見ない。** 画像は文字を持たない葉なので、`textContent` で見ると
387
+ * 画像 1 つの段落が「空行」と判定され、書き出しから丸ごと落ちる。
388
+ * 文字以外の内容を持つ段落は、空行ではない。
389
+ */
367
390
  function isBlank(node) {
368
- if (node.textContent.trim() !== '')
369
- return false;
370
391
  let blank = true;
371
392
  node.forEach((child) => {
372
- if (child.type !== n.paragraph)
393
+ if (child.type !== n.paragraph) {
373
394
  blank = false;
395
+ return;
396
+ }
397
+ child.forEach((inline) => {
398
+ if (!inline.isText)
399
+ blank = false;
400
+ });
374
401
  });
375
- return blank;
402
+ return blank && node.textContent.trim() === '';
376
403
  }
377
404
  /**
378
405
  * 記号だけの行に続くブロックを、空行を挟まずに書く。
@@ -1,5 +1,5 @@
1
1
  import { outlineSchema } from '../document/schema';
2
- import { sectionTree } from '../document/sectionTree';
2
+ import { headingText, sectionTree } from '../document/sectionTree';
3
3
  import { isViewState } from './viewState.types';
4
4
  const SECTION = outlineSchema.nodes.section;
5
5
  /** 形式の版。将来の変更で増やし、古い側は「未対応」として安全に無視できるようにする */
@@ -152,7 +152,7 @@ function keyOf(path) {
152
152
  function hashOfChain(chain) {
153
153
  let hash = 0x811c9dc5;
154
154
  for (const section of chain) {
155
- hash = mix(hash, section.child(0).textContent);
155
+ hash = mix(hash, headingText(section.child(0)));
156
156
  // 区切りを混ぜる。混ぜないと「AB / C」と「A / BC」が同じ値になる
157
157
  hash = step(hash, 0x1f);
158
158
  }
@@ -27,6 +27,23 @@ export const autoformatRules = [
27
27
  textblockTypeInputRule(/^```mermaid[\s\n]$/, outlineSchema.nodes.mermaid_block),
28
28
  textblockTypeInputRule(/^```([a-zA-Z0-9_+#-]*)[\s\n]$/, outlineSchema.nodes.code_block, (match) => ({ language: match[1] ?? '' })),
29
29
  new InputRule(/^(?:---|___|\*\*\*)$/, (state, _match, start, end) => state.tr.replaceWith(start, end, outlineSchema.nodes.horizontal_rule.create())),
30
+ /**
31
+ * 打った画像記法を、閉じ括弧まで打ち終えた時点で画像にする。
32
+ *
33
+ * **記法の判定を 3 つ目にしたわけではない。** ここが見るのは**打っている途中の 1 行**
34
+ * であり、文書全体を解釈する読み込み(markdown-it)とは役割が違う。取り出す属性は
35
+ * 書き出し(→ `serializer.ts` の `serializeImage`)の鏡である。
36
+ *
37
+ * 代替文字は角括弧を含まない範囲、出どころは空白と丸括弧を含まない範囲に限る。
38
+ * 打っている最中の 1 行で、釣り合いを数える相手がいないためである(込み入った形は
39
+ * 読み込みが受け止める)。記法を解釈しない場所(コードブロック・Mermaid・
40
+ * フロントマター)では、入力規則の仕組み自体が働かない(`code` なブロックを除く)。
41
+ */
42
+ new InputRule(/!\[([^[\]]*)\]\(([^\s()]*)(?:\s+"([^"]*)")?\)$/, (state, match, start, end) => state.tr.replaceWith(start, end, outlineSchema.nodes.image.create({
43
+ src: match[2] ?? '',
44
+ alt: match[1] ?? '',
45
+ title: match[3] ?? null
46
+ }))),
30
47
  markInputRule(/(\*\*([^*]+)\*\*)$/, outlineSchema.marks.strong),
31
48
  markInputRule(/(?:^|[^*])(\*([^*]+)\*)$/, outlineSchema.marks.em),
32
49
  markInputRule(/(~~([^~]+)~~)$/, outlineSchema.marks.strikethrough),
@@ -1,7 +1,7 @@
1
1
  import { Plugin, PluginKey, TextSelection } from 'prosemirror-state';
2
2
  import { Decoration, DecorationSet } from 'prosemirror-view';
3
3
  import { outlineSchema } from '../../models/document/schema';
4
- import { sectionTree } from '../../models/document/sectionTree';
4
+ import { headingText, sectionTree } from '../../models/document/sectionTree';
5
5
  import { originOf } from '../transactionOrigin';
6
6
  const SECTION = outlineSchema.nodes.section;
7
7
  /** 範囲外のブロックに付ける印。隠すかどうかの決定は CSS に委ねる */
@@ -324,7 +324,7 @@ function breadcrumbOf(doc, anchorPos) {
324
324
  chain.push(self);
325
325
  return chain
326
326
  .filter((ref) => ref.path !== null)
327
- .map((ref) => ({ path: ref.path, title: ref.node.child(0).textContent }));
327
+ .map((ref) => ({ path: ref.path, title: headingText(ref.node.child(0)) }));
328
328
  }
329
329
  /**
330
330
  * 解除時に戻すためのスクロール位置。
@@ -0,0 +1,26 @@
1
+ import { Plugin } from 'prosemirror-state';
2
+ import { DecorationSet } from 'prosemirror-view';
3
+ /**
4
+ * 貼り付けられた画像を引き受け、表示に使う URL を返す。
5
+ * 保存先・形式やサイズの判定・アクセス制御は呼び出し側の裁量である。
6
+ * 失敗は reject または `null` で表す。
7
+ */
8
+ export type ImageUpload = (file: File) => Promise<string | null>;
9
+ /** 呼ぶ時点の引き受け先を返す。渡されていなければ `undefined`(要件 4.4) */
10
+ export type ImageUploadSource = () => ImageUpload | undefined;
11
+ /** 待っているあいだの表示に使う文言 */
12
+ export interface ImagePasteText {
13
+ readonly uploading: string;
14
+ }
15
+ /**
16
+ * 貼り付けられた画像を引き受け、返された URL で画像を差し込む。
17
+ *
18
+ * **文書は、引き受け先が答えるまで 1 文字も変わらない。** 待っているあいだ置くのは
19
+ * decoration の印だけで、それは文書ではない(書き出しにも現れない)。失敗したときに
20
+ * 「無かった状態へ戻す」が印を消すだけで済むのは、この形の帰結である。
21
+ *
22
+ * **譲る条件は 4 つあり、すべて委譲の前にある**(要件 4.4・4.5・6.1)。1 つでも偽なら
23
+ * `false` を返し、後段の貼り付け(`markdownClipboard`)が従来どおり働く。譲る側の条件を
24
+ * **登録順で表す**ため、このプラグインは `markdownClipboard` より前に置く。
25
+ */
26
+ export declare function imagePastePlugin(getUpload: ImageUploadSource, getText: () => ImagePasteText): Plugin<DecorationSet>;
@@ -0,0 +1,178 @@
1
+ import { closeHistory } from 'prosemirror-history';
2
+ import { AllSelection, NodeSelection, Plugin, PluginKey } from 'prosemirror-state';
3
+ import { Decoration, DecorationSet } from 'prosemirror-view';
4
+ import { outlineSchema } from '../../models/document/schema';
5
+ const IMAGE = outlineSchema.nodes.image;
6
+ const imagePasteKey = new PluginKey('imagePaste');
7
+ /**
8
+ * 貼り付けられた画像を引き受け、返された URL で画像を差し込む。
9
+ *
10
+ * **文書は、引き受け先が答えるまで 1 文字も変わらない。** 待っているあいだ置くのは
11
+ * decoration の印だけで、それは文書ではない(書き出しにも現れない)。失敗したときに
12
+ * 「無かった状態へ戻す」が印を消すだけで済むのは、この形の帰結である。
13
+ *
14
+ * **譲る条件は 4 つあり、すべて委譲の前にある**(要件 4.4・4.5・6.1)。1 つでも偽なら
15
+ * `false` を返し、後段の貼り付け(`markdownClipboard`)が従来どおり働く。譲る側の条件を
16
+ * **登録順で表す**ため、このプラグインは `markdownClipboard` より前に置く。
17
+ */
18
+ export function imagePastePlugin(getUpload, getText) {
19
+ return new Plugin({
20
+ key: imagePasteKey,
21
+ state: {
22
+ init: () => DecorationSet.empty,
23
+ /** 印は文書の編集に付いて動く。足し引きは meta で受ける */
24
+ apply(tr, set) {
25
+ const mapped = set.map(tr.mapping, tr.doc);
26
+ const meta = tr.getMeta(imagePasteKey);
27
+ if (!meta)
28
+ return mapped;
29
+ if (meta.kind === 'add')
30
+ return mapped.add(tr.doc, placeholdersOf(meta, getText));
31
+ const dropped = mapped.remove(mapped.find(undefined, undefined, (spec) => spec.imagePlaceholder === meta.id));
32
+ // 置き換える先は、画像が入った時点か、その貼り付けの印が尽きた時点で用済みになる
33
+ const keepRange = meta.kind === 'drop' && placeholdersLeft(dropped, meta.batch) > 0;
34
+ return keepRange ? dropped : withoutRange(dropped, meta.batch);
35
+ }
36
+ },
37
+ props: {
38
+ decorations: (state) => imagePasteKey.getState(state),
39
+ handlePaste: (view, event) => handlePaste(view, event, getUpload)
40
+ }
41
+ });
42
+ }
43
+ /**
44
+ * 印を作る。**枚数ぶんを同じ位置に置き、順番を持たせる**(要件 4.6)。
45
+ *
46
+ * `side` が正の印は、その位置へ入った内容の**後ろ**へ写る。1 枚目を挿入しても
47
+ * 2 枚目以降の印は画像の後ろに残り、印どうしの前後関係も保たれる。したがって
48
+ * 並び順は解決の順にも枚数にも依存しない。
49
+ *
50
+ * 文言は印を描くたびに読み直す(描き出しを関数で渡す)。
51
+ */
52
+ function placeholdersOf(meta, getText) {
53
+ const decorations = meta.ids.map((id, index) => Decoration.widget(meta.pos, () => placeholderElement(getText().uploading), {
54
+ imagePlaceholder: id,
55
+ imageBatch: meta.batch,
56
+ side: index + 1
57
+ }));
58
+ if (meta.replaces) {
59
+ decorations.push(Decoration.inline(meta.replaces.from, meta.replaces.to, {}, { imageRange: meta.batch }));
60
+ }
61
+ return decorations;
62
+ }
63
+ function placeholderElement(text) {
64
+ const element = document.createElement('span');
65
+ element.className = 'markdown-editor__image-placeholder';
66
+ element.contentEditable = 'false';
67
+ element.textContent = text;
68
+ return element;
69
+ }
70
+ function placeholdersLeft(set, batch) {
71
+ return set.find(undefined, undefined, (spec) => spec.imageBatch === batch && spec.imagePlaceholder !== undefined).length;
72
+ }
73
+ function withoutRange(set, batch) {
74
+ return set.remove(set.find(undefined, undefined, (spec) => spec.imageRange === batch));
75
+ }
76
+ // --- 貼り付けの受け止め ---
77
+ function handlePaste(view, event, getUpload) {
78
+ // 読み取り専用では引き受け先を呼ばない(要件 6.1)
79
+ if (!view.editable)
80
+ return false;
81
+ // 引き受け先が渡されていなければ、画像の貼り付けに何もしない(要件 4.4)
82
+ const upload = getUpload();
83
+ if (!upload)
84
+ return false;
85
+ /**
86
+ * 選択の形。**文書全体を選んでいるとき(差し替えという別の意味を既に持つ)と、
87
+ * ブロックを指しているとき(インラインの画像では置き換えられない)は譲る。**
88
+ * 成立しない操作を試すより、譲って何も起きない方が安全である。
89
+ */
90
+ const { selection } = view.state;
91
+ if (selection instanceof AllSelection || selection instanceof NodeSelection)
92
+ return false;
93
+ // 見るのは「画像ファイルがあるか」だけ。形式・大きさ・中身は見ない(要件 4.2)
94
+ const files = imageFilesOf(event.clipboardData);
95
+ if (files.length === 0)
96
+ return false;
97
+ // その位置に画像を置けるか。種別の表を持たず、内容の定義へ問う(要件 4.5 の延長)
98
+ if (!canPlaceImage(view.state))
99
+ return false;
100
+ startUploads(view, files, upload);
101
+ return true;
102
+ }
103
+ /**
104
+ * クリップボードの画像ファイル。**画像ファイルがあれば、同時に届く HTML や文字より
105
+ * 優先する**(ブラウザからの画像コピーは両方を含み、HTML の側は読み込み規則が無く落ちる)。
106
+ */
107
+ function imageFilesOf(data) {
108
+ if (!data)
109
+ return [];
110
+ return Array.from(data.files).filter((file) => file.type.startsWith('image/'));
111
+ }
112
+ function canPlaceImage(state) {
113
+ const $from = state.selection.$from;
114
+ return $from.parent.canReplaceWith($from.index(), $from.index(), IMAGE);
115
+ }
116
+ /**
117
+ * 印を先に置き、引き受け先を**貼り付けられた順に**呼ぶ。
118
+ *
119
+ * 印の出し入れは取り消し履歴に積まない(要件 5.3)。同時に走らせないのは、
120
+ * 呼び出し側の通信をどう並べるかがモジュールの決めてよい範囲を越えるためである。
121
+ */
122
+ function startUploads(view, files, upload) {
123
+ const batch = Symbol('image-paste');
124
+ const ids = files.map(() => Symbol('image-placeholder'));
125
+ const { from, to } = view.state.selection;
126
+ const meta = {
127
+ kind: 'add',
128
+ batch,
129
+ ids,
130
+ pos: from,
131
+ replaces: from < to ? { from, to } : null
132
+ };
133
+ view.dispatch(view.state.tr.setMeta(imagePasteKey, meta).setMeta('addToHistory', false));
134
+ void resolveInOrder(view, files, ids, batch, upload);
135
+ }
136
+ async function resolveInOrder(view, files, ids, batch, upload) {
137
+ for (let index = 0; index < files.length; index += 1) {
138
+ let url;
139
+ try {
140
+ url = await upload(files[index]);
141
+ }
142
+ catch {
143
+ // 拒否も失敗を表す値も、同じ「引き受けられなかった」である
144
+ url = null;
145
+ }
146
+ settle(view, ids[index], batch, url);
147
+ }
148
+ }
149
+ /**
150
+ * 1 枚ぶんの結果を文書へ反映する。
151
+ *
152
+ * 印が文書から失われていたら(範囲ごと削除された・文書が差し替わった)何も入れない。
153
+ * 失敗のときは印を消すだけで、文書は貼り付けが無かったままである(要件 5.2)。
154
+ */
155
+ function settle(view, id, batch, url) {
156
+ const set = imagePasteKey.getState(view.state);
157
+ const found = set?.find(undefined, undefined, (spec) => spec.imagePlaceholder === id);
158
+ if (!set || !found || found.length === 0)
159
+ return;
160
+ if (url === null) {
161
+ const meta = { kind: 'drop', batch, id };
162
+ view.dispatch(view.state.tr.setMeta(imagePasteKey, meta).setMeta('addToHistory', false));
163
+ return;
164
+ }
165
+ // 代替文字は空にする。ファイル名は説明ではなく、書き手が後から書くものである
166
+ const image = IMAGE.create({ src: url, alt: '', title: null });
167
+ const range = set
168
+ .find(undefined, undefined, (spec) => spec.imageRange === batch)
169
+ .at(0);
170
+ const tr = view.state.tr;
171
+ if (range)
172
+ tr.replaceWith(range.from, range.to, image);
173
+ else
174
+ tr.insert(found[0].from, image);
175
+ const meta = { kind: 'inserted', batch, id };
176
+ // 直前の編集と混ざらない 1 つの取り消し単位にする(要件 5.4)
177
+ view.dispatch(closeHistory(tr.setMeta(imagePasteKey, meta)));
178
+ }
@@ -0,0 +1,16 @@
1
+ import { Plugin } from 'prosemirror-state';
2
+ /** 画像が画面に出す文言。`EditorMessages` から editorSession が写す */
3
+ export interface ImageViewText {
4
+ /** 読み込みに失敗したことを伝える表示 */
5
+ readonly loadError: string;
6
+ }
7
+ /**
8
+ * 画像の NodeView。
9
+ *
10
+ * **`toDOM` では足りない。** 読み込みに失敗したかは DOM の出来事(`error`)でしか
11
+ * 得られず、失敗が分かる表示をその位置に出すには、出来事を聞ける NodeView が要る。
12
+ *
13
+ * `getText` は呼び出し時点の文言を返す(言語・差し替えの変更に追随させるため関数で渡す。
14
+ * `mermaidViewPlugin` と同じ作法)。
15
+ */
16
+ export declare function imageViewPlugin(getText: () => ImageViewText): Plugin;
@@ -0,0 +1,102 @@
1
+ import { Plugin } from 'prosemirror-state';
2
+ import { outlineSchema } from '../../models/document/schema';
3
+ const IMAGE = outlineSchema.nodes.image;
4
+ /**
5
+ * 画像の NodeView。
6
+ *
7
+ * **`toDOM` では足りない。** 読み込みに失敗したかは DOM の出来事(`error`)でしか
8
+ * 得られず、失敗が分かる表示をその位置に出すには、出来事を聞ける NodeView が要る。
9
+ *
10
+ * `getText` は呼び出し時点の文言を返す(言語・差し替えの変更に追随させるため関数で渡す。
11
+ * `mermaidViewPlugin` と同じ作法)。
12
+ */
13
+ export function imageViewPlugin(getText) {
14
+ return new Plugin({
15
+ props: {
16
+ nodeViews: {
17
+ image: (node) => new ImageNodeView(node, getText)
18
+ }
19
+ }
20
+ });
21
+ }
22
+ /**
23
+ * 画像と、その状態表示を並べる。
24
+ *
25
+ * 状態は class と `data-image-state` に写すだけにし、**見た目は CSS が持つ**
26
+ * (`mermaidView` と同じ形)。読み込み状態は文書には現れない。
27
+ */
28
+ class ImageNodeView {
29
+ dom;
30
+ picture;
31
+ status;
32
+ getText;
33
+ src;
34
+ destroyed = false;
35
+ constructor(node, getText) {
36
+ this.getText = getText;
37
+ this.dom = document.createElement('span');
38
+ this.dom.className = 'markdown-editor__image';
39
+ // 中身は編集の対象にしない(画像は中身を持たない葉である)
40
+ this.dom.contentEditable = 'false';
41
+ this.picture = document.createElement('img');
42
+ // 素の描き出し(`toDOM`)でも同じ名前を持つ。あちらは包む要素を持たないだけである
43
+ this.picture.className = 'markdown-editor__image-preview';
44
+ this.picture.addEventListener('load', () => this.setState('loaded'));
45
+ this.picture.addEventListener('error', () => this.setState('failed'));
46
+ this.status = document.createElement('span');
47
+ this.status.className = 'markdown-editor__image-status';
48
+ this.dom.append(this.picture, this.status);
49
+ this.src = String(node.attrs.src ?? '');
50
+ this.writeText(node);
51
+ this.load();
52
+ }
53
+ update(node) {
54
+ if (node.type !== IMAGE)
55
+ return false;
56
+ this.writeText(node);
57
+ const src = String(node.attrs.src ?? '');
58
+ if (src !== this.src) {
59
+ this.src = src;
60
+ this.load();
61
+ }
62
+ return true;
63
+ }
64
+ /** 中身を持たない葉なので、この配下の変化はすべて自分のものである */
65
+ ignoreMutation() {
66
+ return true;
67
+ }
68
+ destroy() {
69
+ this.destroyed = true;
70
+ }
71
+ /** 代替文字とタイトルは属性の写し。読み込みには関わらない */
72
+ writeText(node) {
73
+ this.picture.alt = String(node.attrs.alt ?? '');
74
+ const title = node.attrs.title;
75
+ if (title)
76
+ this.picture.title = String(title);
77
+ else
78
+ this.picture.removeAttribute('title');
79
+ }
80
+ /**
81
+ * 出どころを読み込む。**空の出どころは、届かない出どころと同じに扱う**
82
+ * (`![alt]()` と書かれた文書。`img` に空を渡すと出来事が実行環境ごとに変わる)。
83
+ */
84
+ load() {
85
+ if (!this.src) {
86
+ this.picture.removeAttribute('src');
87
+ this.setState('failed');
88
+ return;
89
+ }
90
+ this.setState('loading');
91
+ this.picture.setAttribute('src', this.src);
92
+ }
93
+ /** 状態を `data-image-state` と modifier class に写す。文言は表示のたびに読み直す */
94
+ setState(state) {
95
+ if (this.destroyed)
96
+ return;
97
+ this.dom.dataset.imageState = state;
98
+ this.dom.classList.toggle('markdown-editor__image--loading', state === 'loading');
99
+ this.dom.classList.toggle('markdown-editor__image--failed', state === 'failed');
100
+ this.status.textContent = state === 'failed' ? this.getText().loadError : '';
101
+ }
102
+ }
@@ -10,6 +10,8 @@ import { editorKeymap } from '../operations/keymap/assemble';
10
10
  import { DEFAULT_LANG, resolveMessages } from '../messages';
11
11
  import { sectionViewPlugin } from '../operations/plugins/sectionView';
12
12
  import { mermaidViewPlugin } from '../operations/plugins/mermaidView';
13
+ import { imagePastePlugin } from '../operations/plugins/imagePaste';
14
+ import { imageViewPlugin } from '../operations/plugins/imageView';
13
15
  import { blockHandlePlugin } from '../operations/plugins/blockHandle';
14
16
  import { frontMatterGuardPlugin } from '../operations/plugins/frontMatterGuard';
15
17
  import { frontMatterViewPlugin } from '../operations/plugins/frontMatterView';
@@ -39,10 +41,13 @@ export function createEditorSession(element, options) {
39
41
  label: options.label,
40
42
  lang: options.lang,
41
43
  mermaidText: options.mermaidText,
42
- frontMatterText: options.frontMatterText
44
+ frontMatterText: options.frontMatterText,
45
+ imageText: options.imageText
43
46
  };
44
47
  let cachedMarkdown = '';
45
48
  const listeners = new Set();
49
+ /** 画像の文言。**貼り付けと表示の 2 つが同じものを読む**(読むたびに最新を返す) */
50
+ const imageText = () => presentation.imageText ?? defaultImageText();
46
51
  const plugins = [
47
52
  // 上下キーが押されたことの記録は、**キーの割り当てより前**に置く。
48
53
  // 後ろに置くと、割り当てが受け止めたキー(表のセル移動など)を見逃し、
@@ -59,6 +64,10 @@ export function createEditorSession(element, options) {
59
64
  // **拡張より前**に置く。`appendTransaction` は並び順に走り、フォーカスの拡張も
60
65
  // 解除時に選択を書き換えるため、後ろにあるとその復元先を上書きしてしまう
61
66
  frontMatterGuardPlugin(),
67
+ // 画像の貼り付けは**通常の貼り付けより前**に置く。譲る条件が並び順で決まる
68
+ // (画像ファイルが無い・引き受け先が無い・置けない位置なら `false` を返し、
69
+ // 後段の `markdownClipboard` が従来どおり働く)
70
+ imagePastePlugin(options.imageUpload ?? (() => undefined), () => imageText()),
62
71
  markdownClipboardPlugin(),
63
72
  gapCursor(),
64
73
  // 表そのものを指す選択を保つ。既定では全セルを覆うセル範囲の選択へ変換され、
@@ -76,6 +85,7 @@ export function createEditorSession(element, options) {
76
85
  editable: !presentation.readonly
77
86
  })),
78
87
  mermaidViewPlugin(() => presentation.mermaidText ?? defaultMermaidText()),
88
+ imageViewPlugin(() => imageText()),
79
89
  ...extensions.flatMap((extension) => extension.plugins)
80
90
  ];
81
91
  const view = new EditorView(element, {
@@ -176,7 +186,8 @@ export function createEditorSession(element, options) {
176
186
  merged.label === presentation.label &&
177
187
  merged.lang === presentation.lang &&
178
188
  merged.frontMatterText === presentation.frontMatterText &&
179
- sameMermaidText(merged.mermaidText, presentation.mermaidText)) {
189
+ sameMermaidText(merged.mermaidText, presentation.mermaidText) &&
190
+ sameImageText(merged.imageText, presentation.imageText)) {
180
191
  return;
181
192
  }
182
193
  presentation = merged;
@@ -221,6 +232,11 @@ function surfaceAttributes(presentation) {
221
232
  function defaultFrontMatterText() {
222
233
  return resolveMessages().frontMatterLabel;
223
234
  }
235
+ /** 画像の文言。渡されていなければ既定言語の文言(読むたびに最新を返す) */
236
+ function defaultImageText() {
237
+ const messages = resolveMessages();
238
+ return { uploading: messages.imageUploading, loadError: messages.imageLoadError };
239
+ }
224
240
  /** 文言が渡されなかったときに使う、既定言語の文言 */
225
241
  function defaultMermaidText() {
226
242
  const messages = resolveMessages();
@@ -231,6 +247,13 @@ function defaultMermaidText() {
231
247
  loadError: messages.mermaidLoadError
232
248
  };
233
249
  }
250
+ function sameImageText(a, b) {
251
+ if (a === b)
252
+ return true;
253
+ if (!a || !b)
254
+ return false;
255
+ return a.uploading === b.uploading && a.loadError === b.loadError;
256
+ }
234
257
  /** 文言は呼び出しごとに新しいオブジェクトで届くため、参照ではなく中身で比べる */
235
258
  function sameMermaidText(a, b) {
236
259
  if (a === b)
@@ -3,7 +3,15 @@ import type { EditorView } from 'prosemirror-view';
3
3
  import type { FrontMatterFields, FrontMatterWriteError, FrontMatterWriteOutcome, MarkdownParseError } from '../models/markdown/markdown.types';
4
4
  import type { Result } from '../utils/result.types';
5
5
  import type { EditorAction } from '../operations/operations.types';
6
+ import type { ImagePasteText, ImageUploadSource } from '../operations/plugins/imagePaste';
7
+ import type { ImageViewText } from '../operations/plugins/imageView';
6
8
  import type { MermaidBlockText } from '../operations/plugins/mermaidView';
9
+ /**
10
+ * 画像が出す文言。**2 つのプラグイン(貼り付けと表示)が読む先を 1 つにまとめる。**
11
+ * 分けて持つと、同じ画像の文言を 2 か所へ渡すことになる。
12
+ */
13
+ export interface ImageText extends ImagePasteText, ImageViewText {
14
+ }
7
15
  /** 内部拡張の注入点。プラグイン列と操作の宣言の 2 種類に限る */
8
16
  export interface EditorExtension {
9
17
  readonly plugins: readonly Plugin[];
@@ -31,10 +39,19 @@ export interface EditorPresentation {
31
39
  readonly mermaidText?: MermaidBlockText;
32
40
  /** フロントマターにタイトルが無いときに出す名前。未指定なら既定言語の文言 */
33
41
  readonly frontMatterText?: string;
42
+ /** 画像の文言(待っているあいだ・読み込みに失敗した)。未指定なら既定言語の文言 */
43
+ readonly imageText?: ImageText;
34
44
  }
35
45
  export interface EditorSessionOptions extends EditorPresentation {
36
46
  readonly initialMarkdown: string;
37
47
  readonly extensions?: readonly EditorExtension[];
48
+ /**
49
+ * 貼り付けられた画像の引き受け先。**値ではなく「呼ぶ時点で読む形」で受け取る。**
50
+ *
51
+ * `presentation` へ載せると等価判定を通ることになり、同一性が毎回変わる関数では
52
+ * `view.setProps` が呼ばれて入力が取りこぼされる(→ `setPresentation` の注)。
53
+ */
54
+ readonly imageUpload?: ImageUploadSource;
38
55
  }
39
56
  export interface EditorSession {
40
57
  getMarkdown(): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@14ch/svelte-md-outliner",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "An outliner-style Markdown editor for Svelte 5. Headings form a real section tree you can fold, focus, and re-nest from the keyboard.",