@14ch/svelte-md-outliner 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/README.ja.md +190 -0
  2. package/README.md +190 -0
  3. package/dist/assets/styles/editor.css +1459 -0
  4. package/dist/assets/styles/theme.css +486 -0
  5. package/dist/components/ContextMenu.svelte +279 -0
  6. package/dist/components/ContextMenu.svelte.d.ts +9 -0
  7. package/dist/components/EditorSurface.svelte +99 -0
  8. package/dist/components/EditorSurface.svelte.d.ts +16 -0
  9. package/dist/components/FocusBreadcrumb.svelte +138 -0
  10. package/dist/components/FocusBreadcrumb.svelte.d.ts +16 -0
  11. package/dist/components/MarkdownEditor.svelte +393 -0
  12. package/dist/components/MarkdownEditor.svelte.d.ts +119 -0
  13. package/dist/components/ShortcutHelpDialog.svelte +155 -0
  14. package/dist/components/ShortcutHelpDialog.svelte.d.ts +12 -0
  15. package/dist/components/internal/Dialog.svelte +157 -0
  16. package/dist/components/internal/Dialog.svelte.d.ts +23 -0
  17. package/dist/components/internal/Modal.svelte +181 -0
  18. package/dist/components/internal/Modal.svelte.d.ts +18 -0
  19. package/dist/components/internal/Popup.svelte +248 -0
  20. package/dist/components/internal/Popup.svelte.d.ts +26 -0
  21. package/dist/index.d.ts +32 -0
  22. package/dist/index.js +28 -0
  23. package/dist/markdown.d.ts +13 -0
  24. package/dist/markdown.js +10 -0
  25. package/dist/messages/en.d.ts +2 -0
  26. package/dist/messages/en.js +107 -0
  27. package/dist/messages/index.d.ts +13 -0
  28. package/dist/messages/index.js +31 -0
  29. package/dist/messages/ja.d.ts +2 -0
  30. package/dist/messages/ja.js +112 -0
  31. package/dist/messages/messages.types.d.ts +59 -0
  32. package/dist/messages/messages.types.js +1 -0
  33. package/dist/models/document/bodySelection.d.ts +32 -0
  34. package/dist/models/document/bodySelection.js +43 -0
  35. package/dist/models/document/document.types.d.ts +27 -0
  36. package/dist/models/document/document.types.js +8 -0
  37. package/dist/models/document/foldable.d.ts +18 -0
  38. package/dist/models/document/foldable.js +21 -0
  39. package/dist/models/document/schema.d.ts +2 -0
  40. package/dist/models/document/schema.js +428 -0
  41. package/dist/models/document/sectionTree.d.ts +15 -0
  42. package/dist/models/document/sectionTree.js +123 -0
  43. package/dist/models/markdown/blockOutline.d.ts +9 -0
  44. package/dist/models/markdown/blockOutline.js +82 -0
  45. package/dist/models/markdown/frontMatter.d.ts +98 -0
  46. package/dist/models/markdown/frontMatter.js +300 -0
  47. package/dist/models/markdown/markdown.types.d.ts +60 -0
  48. package/dist/models/markdown/markdown.types.js +1 -0
  49. package/dist/models/markdown/markdownIt.d.ts +1 -0
  50. package/dist/models/markdown/markdownIt.js +92 -0
  51. package/dist/models/markdown/parser.d.ts +4 -0
  52. package/dist/models/markdown/parser.js +505 -0
  53. package/dist/models/markdown/plainText.d.ts +1 -0
  54. package/dist/models/markdown/plainText.js +25 -0
  55. package/dist/models/markdown/serializer.d.ts +17 -0
  56. package/dist/models/markdown/serializer.js +453 -0
  57. package/dist/models/viewState/viewState.types.d.ts +38 -0
  58. package/dist/models/viewState/viewState.types.js +17 -0
  59. package/dist/models/viewState/viewStateCodec.d.ts +31 -0
  60. package/dist/models/viewState/viewStateCodec.js +173 -0
  61. package/dist/operations/autoformat.d.ts +9 -0
  62. package/dist/operations/autoformat.js +86 -0
  63. package/dist/operations/commands/block.d.ts +24 -0
  64. package/dist/operations/commands/block.js +139 -0
  65. package/dist/operations/commands/codeBlock.d.ts +7 -0
  66. package/dist/operations/commands/codeBlock.js +26 -0
  67. package/dist/operations/commands/element.d.ts +67 -0
  68. package/dist/operations/commands/element.js +269 -0
  69. package/dist/operations/commands/frontMatter.d.ts +35 -0
  70. package/dist/operations/commands/frontMatter.js +120 -0
  71. package/dist/operations/commands/lineBreak.d.ts +9 -0
  72. package/dist/operations/commands/lineBreak.js +16 -0
  73. package/dist/operations/commands/link.d.ts +7 -0
  74. package/dist/operations/commands/link.js +21 -0
  75. package/dist/operations/commands/list.d.ts +126 -0
  76. package/dist/operations/commands/list.js +652 -0
  77. package/dist/operations/commands/mermaidBlock.d.ts +9 -0
  78. package/dist/operations/commands/mermaidBlock.js +28 -0
  79. package/dist/operations/commands/section.d.ts +217 -0
  80. package/dist/operations/commands/section.js +865 -0
  81. package/dist/operations/commands/sectionFold.d.ts +36 -0
  82. package/dist/operations/commands/sectionFold.js +219 -0
  83. package/dist/operations/commands/sectionJump.d.ts +8 -0
  84. package/dist/operations/commands/sectionJump.js +144 -0
  85. package/dist/operations/commands/selectedBlock.d.ts +37 -0
  86. package/dist/operations/commands/selectedBlock.js +170 -0
  87. package/dist/operations/commands/table.d.ts +64 -0
  88. package/dist/operations/commands/table.js +437 -0
  89. package/dist/operations/keymap/assemble.d.ts +22 -0
  90. package/dist/operations/keymap/assemble.js +165 -0
  91. package/dist/operations/keymap/coreActions.d.ts +2 -0
  92. package/dist/operations/keymap/coreActions.js +711 -0
  93. package/dist/operations/keymap/menuItems.d.ts +52 -0
  94. package/dist/operations/keymap/menuItems.js +114 -0
  95. package/dist/operations/keymap/shortcutKeys.d.ts +42 -0
  96. package/dist/operations/keymap/shortcutKeys.js +114 -0
  97. package/dist/operations/keymap/viewActions.d.ts +30 -0
  98. package/dist/operations/keymap/viewActions.js +182 -0
  99. package/dist/operations/operations.types.d.ts +121 -0
  100. package/dist/operations/operations.types.js +1 -0
  101. package/dist/operations/plugins/blockHandle.d.ts +25 -0
  102. package/dist/operations/plugins/blockHandle.js +112 -0
  103. package/dist/operations/plugins/contextMenu.d.ts +33 -0
  104. package/dist/operations/plugins/contextMenu.js +204 -0
  105. package/dist/operations/plugins/focus.d.ts +39 -0
  106. package/dist/operations/plugins/focus.js +350 -0
  107. package/dist/operations/plugins/foldClick.d.ts +11 -0
  108. package/dist/operations/plugins/foldClick.js +117 -0
  109. package/dist/operations/plugins/foldGuard.d.ts +15 -0
  110. package/dist/operations/plugins/foldGuard.js +31 -0
  111. package/dist/operations/plugins/frontMatterGuard.d.ts +21 -0
  112. package/dist/operations/plugins/frontMatterGuard.js +150 -0
  113. package/dist/operations/plugins/frontMatterView.d.ts +34 -0
  114. package/dist/operations/plugins/frontMatterView.js +137 -0
  115. package/dist/operations/plugins/linkPaste.d.ts +3 -0
  116. package/dist/operations/plugins/linkPaste.js +20 -0
  117. package/dist/operations/plugins/listStructure.d.ts +13 -0
  118. package/dist/operations/plugins/listStructure.js +18 -0
  119. package/dist/operations/plugins/markdownClipboard.d.ts +8 -0
  120. package/dist/operations/plugins/markdownClipboard.js +208 -0
  121. package/dist/operations/plugins/mermaidView.d.ts +20 -0
  122. package/dist/operations/plugins/mermaidView.js +206 -0
  123. package/dist/operations/plugins/requiredSelectionEntry.d.ts +10 -0
  124. package/dist/operations/plugins/requiredSelectionEntry.js +124 -0
  125. package/dist/operations/plugins/sectionView.d.ts +12 -0
  126. package/dist/operations/plugins/sectionView.js +44 -0
  127. package/dist/operations/plugins/tabEscape.d.ts +21 -0
  128. package/dist/operations/plugins/tabEscape.js +41 -0
  129. package/dist/operations/plugins/tableHandles.d.ts +24 -0
  130. package/dist/operations/plugins/tableHandles.js +89 -0
  131. package/dist/operations/transaction.d.ts +26 -0
  132. package/dist/operations/transaction.js +51 -0
  133. package/dist/operations/transactionOrigin.d.ts +17 -0
  134. package/dist/operations/transactionOrigin.js +9 -0
  135. package/dist/states/contextMenuController.svelte.d.ts +57 -0
  136. package/dist/states/contextMenuController.svelte.js +206 -0
  137. package/dist/states/editorSession.d.ts +12 -0
  138. package/dist/states/editorSession.js +268 -0
  139. package/dist/states/editorSession.types.d.ts +57 -0
  140. package/dist/states/editorSession.types.js +1 -0
  141. package/dist/states/outlineViewController.svelte.d.ts +52 -0
  142. package/dist/states/outlineViewController.svelte.js +134 -0
  143. package/dist/utils/dateText.d.ts +25 -0
  144. package/dist/utils/dateText.js +71 -0
  145. package/dist/utils/geometry.types.d.ts +13 -0
  146. package/dist/utils/geometry.types.js +1 -0
  147. package/dist/utils/json.types.d.ts +4 -0
  148. package/dist/utils/json.types.js +1 -0
  149. package/dist/utils/platform.d.ts +8 -0
  150. package/dist/utils/platform.js +10 -0
  151. package/dist/utils/result.types.d.ts +7 -0
  152. package/dist/utils/result.types.js +1 -0
  153. package/package.json +109 -0
@@ -0,0 +1,17 @@
1
+ import type { Transaction } from 'prosemirror-state';
2
+ /**
3
+ * 変更の由来を Transaction に書き添える。
4
+ *
5
+ * 判定する側(フォーカス範囲外への波及を塞ぐ仕組み)は、変更の内容だけを見ても
6
+ * 「書き手が編集した」のか「利用者のアプリが本文を差し替えた」のかを区別できない。
7
+ * 区別できないまま一律に塞ぐと、利用者の変更が黙って落ちる。
8
+ *
9
+ * - `host`: 利用者のアプリ由来(`bind:value` の反映)。塞がずに通す
10
+ * - `fold`: 折りたたみの切り替え。表示だけを変えるため通す
11
+ * - `metadata`: フロントマターへの項目の書き込み。領域は表示範囲の外にあるため、
12
+ * 印が無ければ黙って落ちる。`host` を流用しないのは、表示範囲を絞る仕組みが
13
+ * `host` を見て連なりを組み直し、書き込みのたびにその組み直しが走るためである
14
+ */
15
+ export type TransactionOrigin = 'host' | 'fold' | 'metadata';
16
+ export declare function markOrigin<T extends Transaction>(transaction: T, origin: TransactionOrigin): T;
17
+ export declare function originOf(transaction: Transaction): TransactionOrigin | null;
@@ -0,0 +1,9 @@
1
+ const ORIGIN = 'markdown-editor:origin';
2
+ export function markOrigin(transaction, origin) {
3
+ transaction.setMeta(ORIGIN, origin);
4
+ return transaction;
5
+ }
6
+ export function originOf(transaction) {
7
+ const origin = transaction.getMeta(ORIGIN);
8
+ return origin === 'host' || origin === 'fold' || origin === 'metadata' ? origin : null;
9
+ }
@@ -0,0 +1,57 @@
1
+ import type { EditorAction, MenuGroup } from '../operations/operations.types';
2
+ import type { AnchorRect } from '../utils/geometry.types';
3
+ import type { EditorExtension, EditorSession } from './editorSession.types';
4
+ export interface ContextMenuControllerOptions {
5
+ /**
6
+ * 現在のセッション。**生き死にの管理はコンポーネントが持つ**ため、
7
+ * コントローラは都度たどるだけで、抱え込まない
8
+ */
9
+ readonly getSession: () => EditorSession | null;
10
+ /**
11
+ * 拡張のアクション。基盤のぶんはコントローラが足す。
12
+ * **畳む・このセクションだけ表示はここからしか来ない**(`outlineViewController` が
13
+ * エディタごとに生成するため、静的に書けない)
14
+ */
15
+ readonly getExtensionActions: () => readonly EditorAction[];
16
+ /** 組み込みのメニューを使うか。使わないならキーも受け止めない */
17
+ readonly isEnabled?: () => boolean;
18
+ }
19
+ export interface ContextMenuController {
20
+ /** 基盤へ渡す拡張。セッション生成より前に取得する */
21
+ readonly extension: EditorExtension;
22
+ readonly isOpen: boolean;
23
+ readonly anchor: AnchorRect | null;
24
+ readonly groups: readonly MenuGroup[];
25
+ /**
26
+ * 代表のキーを表記してよい操作の id。同じキーを分け合う文脈では、
27
+ * キー入力で実際に実行される側にだけ表記を付ける
28
+ */
29
+ readonly keyLabelledIds: readonly string[];
30
+ /**
31
+ * 説明を引く id。文脈で意味が決まる操作だけが、いま起きる向きの id を持つ
32
+ * (持たない操作は操作の id のまま)
33
+ */
34
+ readonly descriptionIds: Readonly<Record<string, string>>;
35
+ /** 選んでいる項目の位置。分類をまたいだ通し番号。何も選んでいなければ `-1` */
36
+ readonly activeIndex: number;
37
+ setActive(index: number): void;
38
+ /** 選んでいる項目を実行して閉じる */
39
+ run(action: EditorAction): void;
40
+ /** 実行せずに閉じる */
41
+ close(): void;
42
+ /**
43
+ * メニューの中で押されたキーを受ける。**キーの判定はここに閉じる。**
44
+ * 描画側は `event.key` を見ない(正規化レイヤーを必ず通す規約)
45
+ */
46
+ handleKey(event: KeyboardEvent): boolean;
47
+ }
48
+ /**
49
+ * メニューの開閉・錨・項目を、エディタ 1 インスタンスに閉じて持つ。
50
+ *
51
+ * **エディタ 1 つにつき 1 つ生成する。** モジュールスコープの可変状態を持たない。
52
+ * **寿命を持たない。** セッションは都度たどるだけで抱え込まない。
53
+ *
54
+ * 開いた時点の項目を保持し、閉じるまで作り直さない。実行は必ず覆いを掛けた経路
55
+ * (`editorKeymap.decorate`)を通し、入口の違いが挙動の違いにならないようにする。
56
+ */
57
+ export declare function createContextMenuController(options: ContextMenuControllerOptions): ContextMenuController;
@@ -0,0 +1,206 @@
1
+ import { editorKeymap } from '../operations/keymap/assemble';
2
+ import { describedIds, keyLabelledActions, menuGroupsFor } from '../operations/keymap/menuItems';
3
+ import { createKeyStrokeMatcher } from '../operations/keymap/shortcutKeys';
4
+ import { createContextMenuShortcut } from '../operations/keymap/viewActions';
5
+ import { createContextMenuPlugin } from '../operations/plugins/contextMenu';
6
+ /**
7
+ * メニューの開閉・錨・項目を、エディタ 1 インスタンスに閉じて持つ。
8
+ *
9
+ * **エディタ 1 つにつき 1 つ生成する。** モジュールスコープの可変状態を持たない。
10
+ * **寿命を持たない。** セッションは都度たどるだけで抱え込まない。
11
+ *
12
+ * 開いた時点の項目を保持し、閉じるまで作り直さない。実行は必ず覆いを掛けた経路
13
+ * (`editorKeymap.decorate`)を通し、入口の違いが挙動の違いにならないようにする。
14
+ */
15
+ export function createContextMenuController(options) {
16
+ let isOpen = $state(false);
17
+ let anchor = $state(null);
18
+ let groups = $state([]);
19
+ let keyLabelledIds = $state([]);
20
+ let descriptionIds = $state({});
21
+ /**
22
+ * 何も選んでいない状態。**開いた直後はここから始める。**
23
+ *
24
+ * 先頭を選んだ状態で開くと、ポインタを乗せていない項目が乗っているように見える
25
+ * (選択中のマーカーと、ポインタが乗っている印が同じ敷き色である)。キーで選び切れる
26
+ * ことは変わらない——下で先頭へ、上で末尾へ入る。
27
+ */
28
+ const NONE = -1;
29
+ let activeIndex = $state(NONE);
30
+ const menu = createContextMenuPlugin({
31
+ onRequest: (view, request) => openWith(view, request),
32
+ isOpen: () => isOpen,
33
+ close
34
+ });
35
+ const extension = {
36
+ plugins: [menu.plugin],
37
+ actions: createContextMenuShortcut(toggleFromKeyboard)
38
+ };
39
+ function viewOf() {
40
+ return options.getSession()?.getView() ?? null;
41
+ }
42
+ /**
43
+ * キーからの開閉。ポインタからの経路と**同じ関数へ合流させる**ことで、
44
+ * 並ぶ項目と選べる項目が同一になる。
45
+ */
46
+ function toggleFromKeyboard() {
47
+ if (options.isEnabled?.() === false)
48
+ return false;
49
+ if (isOpen) {
50
+ close();
51
+ return true;
52
+ }
53
+ const view = viewOf();
54
+ if (!view)
55
+ return false;
56
+ const request = menu.resolveFromSelection(view);
57
+ return request ? openWith(view, request) : false;
58
+ }
59
+ /**
60
+ * 開く条件をすべて満たすときだけ開く。
61
+ * 満たさないときは**開かないことで失敗を表す**(開いたのに何も選べない状態を作らない)。
62
+ */
63
+ function openWith(view, request) {
64
+ if (options.isEnabled?.() === false)
65
+ return false;
66
+ // 変換が確定していないあいだは覆いが実行そのものを止めるため、判定にも入らない
67
+ if (view.composing)
68
+ return false;
69
+ const available = availableActions();
70
+ const next = menuGroupsFor(available, view);
71
+ if (next.length === 0)
72
+ return false;
73
+ groups = next;
74
+ keyLabelledIds = keyLabelledActions(available, next);
75
+ descriptionIds = describedIds(next, view.state);
76
+ anchor = request.anchor;
77
+ activeIndex = NONE;
78
+ isOpen = true;
79
+ menu.setTarget(view, request.target);
80
+ return true;
81
+ }
82
+ /** 基盤 + 表示状態のまとめ役 + メニュー自身の宣言 */
83
+ function availableActions() {
84
+ return [...editorKeymap.coreActions, ...options.getExtensionActions(), ...extension.actions];
85
+ }
86
+ function close() {
87
+ if (!isOpen)
88
+ return;
89
+ isOpen = false;
90
+ anchor = null;
91
+ groups = [];
92
+ keyLabelledIds = [];
93
+ descriptionIds = {};
94
+ activeIndex = NONE;
95
+ const view = viewOf();
96
+ if (!view)
97
+ return;
98
+ menu.setTarget(view, null);
99
+ view.focus();
100
+ }
101
+ function run(action) {
102
+ const view = viewOf();
103
+ if (!view) {
104
+ close();
105
+ return;
106
+ }
107
+ // 実行は開いた時点の選択に対して行う。対象を決め直さない
108
+ editorKeymap.decorate(action)(view.state, view.dispatch.bind(view), view);
109
+ close();
110
+ }
111
+ /** 分類をまたいだ通しの並び。選んでいる位置はこの並びに対する番号である */
112
+ function flatActions() {
113
+ return groups.flatMap((group) => group.actions);
114
+ }
115
+ /**
116
+ * 1 つずつ動かし、端では反対の端へ回り込む。
117
+ * 何も選んでいない状態からは、下で先頭へ、上で末尾へ入る。
118
+ */
119
+ function moveActive(step) {
120
+ const count = flatActions().length;
121
+ if (count === 0)
122
+ return false;
123
+ const from = activeIndex === NONE ? (step > 0 ? NONE : 0) : activeIndex;
124
+ activeIndex = (from + step + count) % count;
125
+ return true;
126
+ }
127
+ function runActive() {
128
+ const action = flatActions()[activeIndex];
129
+ if (!action)
130
+ return false;
131
+ run(action);
132
+ return true;
133
+ }
134
+ /**
135
+ * メニューの中で受けるキー。
136
+ *
137
+ * **メニューは `view.dom` の外に描かれ、フォーカスもそこへ移る**ため、編集基盤の
138
+ * キーバインドは届かない。とはいえ規則は 2 通りにせず、照合器を通す。
139
+ * メニューを閉じるキーは**宣言から引く**ので、`Mod-/` を動かしても書き換えが要らない。
140
+ */
141
+ const matchKey = createKeyStrokeMatcher([
142
+ ...extension.actions.flatMap((action) => action.keys.map((keys) => ({
143
+ keys,
144
+ run: () => {
145
+ close();
146
+ return true;
147
+ }
148
+ }))),
149
+ { keys: { key: 'ArrowDown' }, run: () => moveActive(1) },
150
+ { keys: { key: 'ArrowUp' }, run: () => moveActive(-1) },
151
+ { keys: { key: 'Home' }, run: () => setActive(0) },
152
+ { keys: { key: 'End' }, run: () => setActive(flatActions().length - 1) },
153
+ { keys: { key: 'Enter' }, run: runActive },
154
+ { keys: { key: 'Space' }, run: runActive },
155
+ {
156
+ keys: { key: 'Escape' },
157
+ run: () => {
158
+ close();
159
+ return true;
160
+ }
161
+ }
162
+ ]);
163
+ /** `Tab` は受け止めず、ポップアップの循環に委ねる */
164
+ function handleKey(event) {
165
+ const view = viewOf();
166
+ if (!isOpen || !view)
167
+ return false;
168
+ if (!matchKey(view, event))
169
+ return false;
170
+ event.preventDefault();
171
+ return true;
172
+ }
173
+ function setActive(index) {
174
+ if (index < 0)
175
+ return false;
176
+ activeIndex = index;
177
+ return true;
178
+ }
179
+ return {
180
+ extension,
181
+ get isOpen() {
182
+ return isOpen;
183
+ },
184
+ get anchor() {
185
+ return anchor;
186
+ },
187
+ get groups() {
188
+ return groups;
189
+ },
190
+ get keyLabelledIds() {
191
+ return keyLabelledIds;
192
+ },
193
+ get descriptionIds() {
194
+ return descriptionIds;
195
+ },
196
+ get activeIndex() {
197
+ return activeIndex;
198
+ },
199
+ setActive: (index) => {
200
+ setActive(index);
201
+ },
202
+ run,
203
+ close,
204
+ handleKey
205
+ };
206
+ }
@@ -0,0 +1,12 @@
1
+ import type { MarkdownParseError } from '../models/markdown/markdown.types';
2
+ import type { Result } from '../utils/result.types';
3
+ import type { EditorSession, EditorSessionOptions } from './editorSession.types';
4
+ /**
5
+ * 編集セッションを 1 つ作る。
6
+ *
7
+ * ファクトリであり、モジュールの読み込み時には何も生成しない。プラグインは state を持つため
8
+ * 呼ばれるたびに作り直す。共有すると、同じページの 2 つのエディタが状態を分け合ってしまう。
9
+ *
10
+ * ブラウザでのみ呼ぶ(`EditorView` が DOM を必要とする)。
11
+ */
12
+ export declare function createEditorSession(element: HTMLElement, options: EditorSessionOptions): Result<EditorSession, MarkdownParseError>;
@@ -0,0 +1,268 @@
1
+ import { createListPlugins } from 'prosemirror-flat-list';
2
+ import { gapCursor } from 'prosemirror-gapcursor';
3
+ import { closeHistory, history } from 'prosemirror-history';
4
+ import { EditorState } from 'prosemirror-state';
5
+ import { tableEditing } from 'prosemirror-tables';
6
+ import { EditorView } from 'prosemirror-view';
7
+ import { parseMarkdown } from '../models/markdown/parser';
8
+ import { serializeMarkdown } from '../models/markdown/serializer';
9
+ import { editorKeymap } from '../operations/keymap/assemble';
10
+ import { DEFAULT_LANG, resolveMessages } from '../messages';
11
+ import { sectionViewPlugin } from '../operations/plugins/sectionView';
12
+ import { mermaidViewPlugin } from '../operations/plugins/mermaidView';
13
+ import { blockHandlePlugin } from '../operations/plugins/blockHandle';
14
+ import { frontMatterGuardPlugin } from '../operations/plugins/frontMatterGuard';
15
+ import { frontMatterViewPlugin } from '../operations/plugins/frontMatterView';
16
+ import { listStructurePlugin } from '../operations/plugins/listStructure';
17
+ import { markdownClipboardPlugin } from '../operations/plugins/markdownClipboard';
18
+ import { requiredSelectionEntryPlugin } from '../operations/plugins/requiredSelectionEntry';
19
+ import { tableHandlesPlugin } from '../operations/plugins/tableHandles';
20
+ import { writeFrontMatterFields as writeFrontMatterFieldsCommand } from '../operations/commands/frontMatter';
21
+ import { bodySelection } from '../models/document/bodySelection';
22
+ import { outlineSchema } from '../models/document/schema';
23
+ import { markOrigin } from '../operations/transactionOrigin';
24
+ /**
25
+ * 編集セッションを 1 つ作る。
26
+ *
27
+ * ファクトリであり、モジュールの読み込み時には何も生成しない。プラグインは state を持つため
28
+ * 呼ばれるたびに作り直す。共有すると、同じページの 2 つのエディタが状態を分け合ってしまう。
29
+ *
30
+ * ブラウザでのみ呼ぶ(`EditorView` が DOM を必要とする)。
31
+ */
32
+ export function createEditorSession(element, options) {
33
+ const parsed = parseMarkdown(options.initialMarkdown);
34
+ if (!parsed.ok)
35
+ return parsed;
36
+ const extensions = options.extensions ?? [];
37
+ let presentation = {
38
+ readonly: options.readonly ?? false,
39
+ label: options.label,
40
+ lang: options.lang,
41
+ mermaidText: options.mermaidText,
42
+ frontMatterText: options.frontMatterText
43
+ };
44
+ let cachedMarkdown = '';
45
+ const listeners = new Set();
46
+ const plugins = [
47
+ // 上下キーが押されたことの記録は、**キーの割り当てより前**に置く。
48
+ // 後ろに置くと、割り当てが受け止めたキー(表のセル移動など)を見逃し、
49
+ // 表から出た先の要選択ブロックを指せない
50
+ requiredSelectionEntryPlugin(),
51
+ // 帯の押下は、編集基盤がカーソルを置く前に受け止める必要がある
52
+ blockHandlePlugin(),
53
+ // 基盤の並び順はここが決める。拡張はその後段に置く
54
+ ...editorKeymap.createPlugins(extensions.flatMap((extension) => extension.actions)),
55
+ history(),
56
+ // 全選択の置き換えの見張り。`history` より後ろに置くことで、打った文字を作る
57
+ // transaction が取り消しの対象に入る。貼り付けの分岐は `markdownClipboard` が
58
+ // 持ち、その差し替えは印で見張りの外に置かれる。
59
+ // **拡張より前**に置く。`appendTransaction` は並び順に走り、フォーカスの拡張も
60
+ // 解除時に選択を書き換えるため、後ろにあるとその復元先を上書きしてしまう
61
+ frontMatterGuardPlugin(),
62
+ markdownClipboardPlugin(),
63
+ gapCursor(),
64
+ // 表そのものを指す選択を保つ。既定では全セルを覆うセル範囲の選択へ変換され、
65
+ // 表だけがブロックとして指せない状態になる(セル範囲の選択は変換とは無関係に働く)
66
+ tableEditing({ allowTableNodeSelection: true }),
67
+ tableHandlesPlugin(),
68
+ ...createListPlugins({ schema: outlineSchema }),
69
+ listStructurePlugin(),
70
+ sectionViewPlugin(),
71
+ // NodeView を持つ表示の仕組み。どうしも相互作用しないため、同じ場所へまとめる。
72
+ // 文言は表示を更新するたびに読み直す(差し替えの反映は次の表示更新から)
73
+ frontMatterViewPlugin(() => ({
74
+ label: presentation.frontMatterText ?? defaultFrontMatterText(),
75
+ lang: presentation.lang ?? DEFAULT_LANG,
76
+ editable: !presentation.readonly
77
+ })),
78
+ mermaidViewPlugin(() => presentation.mermaidText ?? defaultMermaidText()),
79
+ ...extensions.flatMap((extension) => extension.plugins)
80
+ ];
81
+ const view = new EditorView(element, {
82
+ state: createState(parsed.value),
83
+ editable: () => !presentation.readonly,
84
+ attributes: () => surfaceAttributes(presentation),
85
+ dispatchTransaction(transaction) {
86
+ view.updateState(view.state.apply(transaction));
87
+ notify(transaction.docChanged);
88
+ }
89
+ });
90
+ cachedMarkdown = serializeMarkdown(view.state.doc);
91
+ /**
92
+ * 編集状態を作る。**カーソルの行き先は生成時に決める。**
93
+ *
94
+ * 生成後に補正する形にすると 2 手に分かれ、片方(文書の入れ替え)を足し忘れる余地が
95
+ * 残る。フロントマターは文書の先頭にあるため、決めずに作るとカーソルがメタデータの中に
96
+ * 立つ。
97
+ */
98
+ function createState(doc) {
99
+ return EditorState.create({
100
+ schema: outlineSchema,
101
+ doc,
102
+ plugins,
103
+ selection: bodySelection(doc)
104
+ });
105
+ }
106
+ /**
107
+ * 購読者へ変化を知らせる。
108
+ *
109
+ * 「文書が変わったか」は**書き出したマークダウンで判定する**。ノードの属性だけが
110
+ * 変わる操作(折りたたみ)は文書の構造としては変更だが、書かれている内容は同じで
111
+ * あり、利用者から見れば何も起きていない。
112
+ *
113
+ * 判定が偽でも購読者は呼ぶ。表示状態の変化は文書を変えないため、ここで捨てると
114
+ * フォーカスの開始・解除が画面へ届かなくなる。
115
+ */
116
+ function notify(structureChanged) {
117
+ // 選択が動いただけのときに書き出し直さない(大きな文書で効く)
118
+ if (structureChanged) {
119
+ const next = serializeMarkdown(view.state.doc);
120
+ const docChanged = next !== cachedMarkdown;
121
+ cachedMarkdown = next;
122
+ publish(docChanged);
123
+ return;
124
+ }
125
+ publish(false);
126
+ }
127
+ function publish(docChanged) {
128
+ const change = { markdown: cachedMarkdown, docChanged };
129
+ for (const listener of listeners)
130
+ listener(change);
131
+ }
132
+ return {
133
+ ok: true,
134
+ value: {
135
+ getMarkdown: () => cachedMarkdown,
136
+ applyMarkdown(markdown) {
137
+ const result = parseMarkdown(markdown);
138
+ if (!result.ok)
139
+ return result;
140
+ const transaction = diffTransaction(view.state, result.value);
141
+ if (!transaction)
142
+ return { ok: true, value: undefined };
143
+ // 直前の文字入力とは独立した取り消し単位にする。
144
+ // 由来を書き添えるのは、表示範囲を絞る仕組みがこれを見て素通しするためである
145
+ // (塞ぐと、利用者が渡した本文が黙って落ちる)
146
+ view.dispatch(markOrigin(closeHistory(transaction), 'host'));
147
+ return { ok: true, value: undefined };
148
+ },
149
+ /**
150
+ * 命令を呼び、変更があれば当てて、結果を返すだけ。**判断を持たない。**
151
+ * 見送り・同値・失敗の決定はいずれも命令の側にある
152
+ */
153
+ writeFrontMatterFields(fields) {
154
+ const result = writeFrontMatterFieldsCommand(view.state, fields);
155
+ if (!result.ok)
156
+ return result;
157
+ if (result.value.transaction)
158
+ view.dispatch(result.value.transaction);
159
+ return { ok: true, value: result.value.outcome };
160
+ },
161
+ resetDocument(markdown) {
162
+ const result = parseMarkdown(markdown);
163
+ if (!result.ok)
164
+ return result;
165
+ // 新しい EditorState を作ることで取り消し履歴も初期化される
166
+ view.updateState(createState(result.value));
167
+ notify(true);
168
+ return { ok: true, value: undefined };
169
+ },
170
+ focus: () => view.focus(),
171
+ setPresentation(next) {
172
+ const merged = { ...presentation, ...next };
173
+ // 中身が同じなら何もしない。`setProps` は表示を組み直すため、
174
+ // 呼ぶたびに DOM 側のカーソル位置が巻き戻り、入力が取りこぼされる
175
+ if (merged.readonly === presentation.readonly &&
176
+ merged.label === presentation.label &&
177
+ merged.lang === presentation.lang &&
178
+ merged.frontMatterText === presentation.frontMatterText &&
179
+ sameMermaidText(merged.mermaidText, presentation.mermaidText)) {
180
+ return;
181
+ }
182
+ presentation = merged;
183
+ // editable と attributes は関数として渡してあるため、再評価させれば反映される。
184
+ // Mermaid の文言はプラグインが読むたびに presentation から取るため、
185
+ // 差し替えは次の表示更新から効く(即時反映は約束しない)
186
+ view.setProps({});
187
+ },
188
+ subscribe(listener) {
189
+ listeners.add(listener);
190
+ return () => listeners.delete(listener);
191
+ },
192
+ destroy() {
193
+ listeners.clear();
194
+ view.destroy();
195
+ },
196
+ getView: () => view
197
+ }
198
+ };
199
+ }
200
+ /**
201
+ * 編集エリアを「複数行のテキストを入力する場所」として支援技術へ伝える。
202
+ * `contenteditable` だけでは編集できる場所として認識されないため、役割と状態を明示する。
203
+ */
204
+ function surfaceAttributes(presentation) {
205
+ const attributes = {
206
+ class: 'markdown-editor__surface',
207
+ role: 'textbox',
208
+ 'aria-multiline': 'true',
209
+ // キーボードだけで編集エリアへ到達できるようにする
210
+ tabindex: '0'
211
+ };
212
+ if (presentation.label)
213
+ attributes['aria-label'] = presentation.label;
214
+ if (presentation.lang)
215
+ attributes.lang = presentation.lang;
216
+ if (presentation.readonly)
217
+ attributes['aria-readonly'] = 'true';
218
+ return attributes;
219
+ }
220
+ /** 文言が渡されなかったときに使う、既定言語の文言 */
221
+ function defaultFrontMatterText() {
222
+ return resolveMessages().frontMatterLabel;
223
+ }
224
+ /** 文言が渡されなかったときに使う、既定言語の文言 */
225
+ function defaultMermaidText() {
226
+ const messages = resolveMessages();
227
+ return {
228
+ empty: messages.mermaidEmpty,
229
+ loading: messages.mermaidLoading,
230
+ renderError: messages.mermaidRenderError,
231
+ loadError: messages.mermaidLoadError
232
+ };
233
+ }
234
+ /** 文言は呼び出しごとに新しいオブジェクトで届くため、参照ではなく中身で比べる */
235
+ function sameMermaidText(a, b) {
236
+ if (a === b)
237
+ return true;
238
+ if (!a || !b)
239
+ return false;
240
+ return (a.empty === b.empty &&
241
+ a.loading === b.loading &&
242
+ a.renderError === b.renderError &&
243
+ a.loadError === b.loadError);
244
+ }
245
+ /**
246
+ * 変わった箇所だけを置き換える Transaction を作る。差分がなければ `null`。
247
+ *
248
+ * 全置換にしないのは、カーソル位置と取り消し履歴を守るためである。
249
+ * 前後の両端から一致する部分を除いて、中間の範囲を 1 回の置換にする
250
+ * (最小差分は求めない。守りたいのはカーソルと履歴であって差分の最小性ではない)。
251
+ */
252
+ function diffTransaction(state, next) {
253
+ const current = state.doc;
254
+ const start = current.content.findDiffStart(next.content);
255
+ if (start === null)
256
+ return null;
257
+ const ends = current.content.findDiffEnd(next.content);
258
+ if (!ends)
259
+ return null;
260
+ let { a: endInCurrent, b: endInNext } = ends;
261
+ // 置換範囲が前方の一致部分へ食い込まないようにそろえる
262
+ const overlap = start - Math.min(endInCurrent, endInNext);
263
+ if (overlap > 0) {
264
+ endInCurrent += overlap;
265
+ endInNext += overlap;
266
+ }
267
+ return state.tr.replace(start, endInCurrent, next.slice(start, endInNext));
268
+ }
@@ -0,0 +1,57 @@
1
+ import type { Plugin } from 'prosemirror-state';
2
+ import type { EditorView } from 'prosemirror-view';
3
+ import type { FrontMatterFields, FrontMatterWriteError, FrontMatterWriteOutcome, MarkdownParseError } from '../models/markdown/markdown.types';
4
+ import type { Result } from '../utils/result.types';
5
+ import type { EditorAction } from '../operations/operations.types';
6
+ import type { MermaidBlockText } from '../operations/plugins/mermaidView';
7
+ /** 内部拡張の注入点。プラグイン列と操作の宣言の 2 種類に限る */
8
+ export interface EditorExtension {
9
+ readonly plugins: readonly Plugin[];
10
+ readonly actions: readonly EditorAction[];
11
+ }
12
+ export interface DocumentChange {
13
+ readonly markdown: string;
14
+ /**
15
+ * 書き出したマークダウンが実際に変わったか。
16
+ * 選択が動いただけのとき、および表示状態だけが変わったとき(折りたたみ)は `false`。
17
+ *
18
+ * 通知そのものの条件ではない。表示状態の変化を捨てないよう、偽のときも購読者は呼ばれる。
19
+ */
20
+ readonly docChanged: boolean;
21
+ }
22
+ export type Unsubscribe = () => void;
23
+ /** 編集エリアの見せ方。文書の中身ではなく、支援技術への伝え方と編集可否を決める */
24
+ export interface EditorPresentation {
25
+ readonly readonly?: boolean;
26
+ /** 編集エリアのアクセシブルな名前 */
27
+ readonly label?: string;
28
+ /** 編集エリアの言語。画面読み上げソフトが正しい発音で読むために使う */
29
+ readonly lang?: string;
30
+ /** Mermaid ブロックの文言。未指定なら既定言語の文言 */
31
+ readonly mermaidText?: MermaidBlockText;
32
+ /** フロントマターにタイトルが無いときに出す名前。未指定なら既定言語の文言 */
33
+ readonly frontMatterText?: string;
34
+ }
35
+ export interface EditorSessionOptions extends EditorPresentation {
36
+ readonly initialMarkdown: string;
37
+ readonly extensions?: readonly EditorExtension[];
38
+ }
39
+ export interface EditorSession {
40
+ getMarkdown(): string;
41
+ /** 差分として適用する。カーソル位置と取り消し履歴を保持する */
42
+ applyMarkdown(markdown: string): Result<void, MarkdownParseError>;
43
+ /** 文書全体を入れ替え、取り消し履歴を初期化する */
44
+ resetDocument(markdown: string): Result<void, MarkdownParseError>;
45
+ /**
46
+ * フロントマターへ項目を書き込む。取り消し履歴に積まず、本文とカーソルを変えない。
47
+ * 利用者がその項目を編集している最中は見送り、`skipped` を返す
48
+ */
49
+ writeFrontMatterFields(fields: FrontMatterFields): Result<FrontMatterWriteOutcome, FrontMatterWriteError>;
50
+ focus(): void;
51
+ /** 読み取り専用・ラベル・言語を差し替える(props の変化に追随させる) */
52
+ setPresentation(presentation: EditorPresentation): void;
53
+ subscribe(listener: (change: DocumentChange) => void): Unsubscribe;
54
+ destroy(): void;
55
+ /** 内部拡張向け。公開 API からは到達できない */
56
+ getView(): EditorView;
57
+ }
@@ -0,0 +1 @@
1
+ export {};