@14ch/svelte-md-outliner 0.0.1 → 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.
Files changed (34) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/LICENSE +21 -0
  3. package/README.ja.md +33 -17
  4. package/README.md +33 -17
  5. package/dist/assets/styles/editor.css +77 -3
  6. package/dist/assets/styles/theme.css +4 -0
  7. package/dist/components/ContextMenu.svelte +12 -3
  8. package/dist/components/MarkdownEditor.svelte +26 -2
  9. package/dist/components/MarkdownEditor.svelte.d.ts +15 -0
  10. package/dist/index.d.ts +5 -0
  11. package/dist/messages/en.js +3 -1
  12. package/dist/messages/index.js +2 -0
  13. package/dist/messages/ja.js +3 -1
  14. package/dist/messages/messages.types.d.ts +6 -0
  15. package/dist/models/document/document.types.d.ts +7 -0
  16. package/dist/models/document/schema.js +98 -18
  17. package/dist/models/document/sectionTree.d.ts +9 -0
  18. package/dist/models/document/sectionTree.js +12 -0
  19. package/dist/models/markdown/parser.js +26 -19
  20. package/dist/models/markdown/serializer.js +65 -6
  21. package/dist/models/viewState/viewStateCodec.js +2 -2
  22. package/dist/operations/autoformat.js +17 -0
  23. package/dist/operations/commands/lineBreak.d.ts +3 -3
  24. package/dist/operations/commands/lineBreak.js +3 -3
  25. package/dist/operations/keymap/coreActions.js +2 -2
  26. package/dist/operations/keymap/viewActions.js +25 -1
  27. package/dist/operations/plugins/focus.js +2 -2
  28. package/dist/operations/plugins/imagePaste.d.ts +26 -0
  29. package/dist/operations/plugins/imagePaste.js +178 -0
  30. package/dist/operations/plugins/imageView.d.ts +16 -0
  31. package/dist/operations/plugins/imageView.js +102 -0
  32. package/dist/states/editorSession.js +25 -2
  33. package/dist/states/editorSession.types.d.ts +17 -0
  34. package/package.json +6 -1
@@ -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.1",
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.",
@@ -22,12 +22,17 @@
22
22
  "type": "git",
23
23
  "url": "git+https://github.com/iyodatakashi/svelte-md-outliner.git"
24
24
  },
25
+ "homepage": "https://github.com/iyodatakashi/svelte-md-outliner#readme",
26
+ "bugs": {
27
+ "url": "https://github.com/iyodatakashi/svelte-md-outliner/issues"
28
+ },
25
29
  "publishConfig": {
26
30
  "access": "public"
27
31
  },
28
32
  "files": [
29
33
  "dist",
30
34
  "README.ja.md",
35
+ "CHANGELOG.md",
31
36
  "!dist/**/*.test.*",
32
37
  "!dist/**/*.spec.*"
33
38
  ],