@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,865 @@
1
+ import { Selection, TextSelection } from 'prosemirror-state';
2
+ import { MAX_HEADING_LEVEL } from '../../models/document/document.types';
3
+ import { bodyCount, bodyIndex, bodyStart } from '../../models/document/bodySelection';
4
+ import { outlineSchema } from '../../models/document/schema';
5
+ import { sectionTree } from '../../models/document/sectionTree';
6
+ import { moveContent, setCursor, syncFrom } from '../transaction';
7
+ const n = outlineSchema.nodes;
8
+ /**
9
+ * 見出しを 1 段深くする。直前の兄弟セクションの中身の末尾へ移す。
10
+ *
11
+ * 直前に兄弟セクションがない場合は何もしない。深くしても親が存在しないため、
12
+ * 深さとレベルを一致させたまま実行できないためである。
13
+ *
14
+ * 選択が複数の見出しにまたがるときは、覆われた見出しをすべて深くする。
15
+ * **前から順に処理する。** 移す先は直前の兄弟なので、前のものが移ったあとは次のものの
16
+ * 直前がその移り先そのものになり、兄弟だったものは兄弟のまま並ぶ。
17
+ */
18
+ export function sinkSection(state, dispatch) {
19
+ const targets = selectedSections(state);
20
+ if (targets.length === 0)
21
+ return false;
22
+ if (targets.some((target) => !canSink(state.doc, target)))
23
+ return false;
24
+ if (!dispatch)
25
+ return true;
26
+ const tr = state.tr;
27
+ const moved = targets.map((target) => {
28
+ const pos = tr.mapping.map(target.pos);
29
+ // 直前の兄弟の中身の末尾は、対象が始まる位置の 1 つ手前である
30
+ const insertAt = pos - 1;
31
+ tr.delete(pos, pos + target.node.nodeSize);
32
+ tr.insert(insertAt, target.node);
33
+ syncFrom(tr, insertAt);
34
+ return { at: insertAt, steps: tr.steps.length };
35
+ });
36
+ restoreSelection(tr, state, targets, moved);
37
+ dispatch(tr.scrollIntoView());
38
+ return true;
39
+ }
40
+ /**
41
+ * 見出しを 1 段浅くする。**セクションを、元の親の配下すべての後ろへ移す。**
42
+ *
43
+ * 後ろにある兄弟のセクションは親の子のまま残り、対象の中身にならない。対象をその場に
44
+ * 留めようとすると、マークダウンに「見出しの後に、その見出しの外側の内容」を書く構文が
45
+ * 無いために取り込むしかなかったが、配下すべての後ろへ移せばその形は生じない。
46
+ *
47
+ * 選択が複数の見出しにまたがるときは、覆われた見出しをすべて浅くする。
48
+ * **後ろから順に処理する。** 対象はそれぞれ親の直後へ入るため、前から処理すると
49
+ * あとの対象が先の対象より手前に入り、対象どうしの並び順が逆になる。
50
+ */
51
+ export function liftSection(state, dispatch) {
52
+ const targets = selectedSections(state);
53
+ if (targets.length === 0)
54
+ return false;
55
+ if (targets.some((target) => !canLift(state.doc, target)))
56
+ return false;
57
+ if (!dispatch)
58
+ return true;
59
+ const tr = state.tr;
60
+ const moved = [];
61
+ for (let index = targets.length - 1; index >= 0; index -= 1) {
62
+ moved[index] = { at: liftOne(tr, tr.mapping.map(targets[index].pos)), steps: tr.steps.length };
63
+ }
64
+ restoreSelection(tr, state, targets, moved);
65
+ dispatch(tr.scrollIntoView());
66
+ return true;
67
+ }
68
+ /** 1 つのセクションを親の次の兄弟へ出す。移り先の位置を返す */
69
+ function liftOne(tr, pos) {
70
+ const $target = tr.doc.resolve(pos);
71
+ const target = $target.nodeAfter;
72
+ const parentEnd = $target.before() + $target.parent.nodeSize;
73
+ const at = moveContent(tr, pos, pos + target.nodeSize, parentEnd);
74
+ syncFrom(tr, at);
75
+ return at;
76
+ }
77
+ /** 直前に兄弟のセクションがあり、配下も最下位レベルを超えないこと */
78
+ function canSink(doc, target) {
79
+ if (!previousSiblingSection(doc, target.pos))
80
+ return false;
81
+ return deepestLevelIn(target.node, target.level) < MAX_HEADING_LEVEL;
82
+ }
83
+ /** 出る先の親があること(最上位のセクションは浅くできない) */
84
+ function canLift(doc, target) {
85
+ const $target = doc.resolve(target.pos);
86
+ return $target.depth > 0 && $target.parent.type === n.section;
87
+ }
88
+ /**
89
+ * 選択が覆っている見出しのセクション。文書順に並ぶ。
90
+ *
91
+ * 対象になるのは**見出しの行が選択に覆われたセクション**だけである。カーソルだけのときは
92
+ * 1 つになり、`targetSection` と同じ結果になる。中身にかかっただけのセクションは入らない
93
+ * (セクションを対象にするには見出しにカーソルを置く、という線引きと同じ)。
94
+ *
95
+ * **配下のセクションは入れない。** 外側が動けば配下は一緒に動くため、別に数えると
96
+ * 二重に動いて相対階層が変わる。
97
+ */
98
+ function selectedSections(state) {
99
+ const first = targetSection(state);
100
+ if (!first)
101
+ return [];
102
+ const to = coveredEnd(state);
103
+ const found = [first];
104
+ const after = first.pos + first.node.nodeSize;
105
+ if (after >= to)
106
+ return found;
107
+ state.doc.nodesBetween(after, to, (node, pos) => {
108
+ if (node.type !== n.section)
109
+ return true;
110
+ // 先頭の対象を含む祖先。まだ後ろに対象がありうるので中を見る
111
+ if (pos < after)
112
+ return true;
113
+ // 見出しの行にかかっていない。中はそれより後ろなので見なくてよい
114
+ if (to <= pos + 1)
115
+ return false;
116
+ const ref = sectionTree.resolveSection(state.doc, pos + 1);
117
+ if (ref && ref.level !== null)
118
+ found.push(ref);
119
+ return false;
120
+ });
121
+ return found;
122
+ }
123
+ /**
124
+ * セクションごと動かした先で、もとの選択を張り直す。
125
+ *
126
+ * セクションを取り除いて入れ直すので、位置の写し取り(`tr.mapping`)ではもとの選択を
127
+ * 追えない。先頭と末尾のセクションの中での隔たりを覚えておき、移り先の同じ隔たりへ置く。
128
+ */
129
+ function restoreSelection(tr, state, targets, moved) {
130
+ const last = targets.length - 1;
131
+ const from = movedPos(tr, targets[0], moved[0], state.selection.from);
132
+ const to = movedPos(tr, targets[last], moved[last], state.selection.to);
133
+ tr.setSelection(TextSelection.between(tr.doc.resolve(from), tr.doc.resolve(to)));
134
+ }
135
+ /** セクションの中の位置を、移り先の同じ隔たりへ置き換える */
136
+ function movedPos(tr, target, moved, pos) {
137
+ const offset = Math.min(Math.max(pos - target.pos, 1), target.node.nodeSize - 1);
138
+ return tr.mapping.slice(moved.steps).map(moved.at) + offset;
139
+ }
140
+ /**
141
+ * 選択が覆っている終わりの位置。
142
+ *
143
+ * **選択の終わりが次の行の先頭にあるとき、その行は覆っていない。** `Shift+↓` は次の行の
144
+ * 先頭へカーソルを進めるため、書き手には 2 行しか選ばれていなくても、位置としては 3 行目に
145
+ * 触れている。触れただけの行まで動かすと、選んだつもりのない行が動く。**触れた位置ではなく、
146
+ * 覆った行で決める**(3 行目に文字が 1 つでも入っていれば覆っている)。
147
+ */
148
+ export function coveredEnd(state) {
149
+ const { $from, $to } = state.selection;
150
+ if ($to.pos <= $from.pos || $to.parentOffset > 0)
151
+ return $to.pos;
152
+ // 直前のテキストブロックの末尾へ戻す。戻した先が始まりを追い越すなら 1 行だけの選択
153
+ const $end = Selection.near(state.doc.resolve($to.pos - 1), -1).$to;
154
+ return Math.max($end.pos, $from.pos);
155
+ }
156
+ /**
157
+ * セクション(見出しとその配下)を、同じ階層の前後の兄弟と入れ替える。
158
+ * 深さは変わらないため、昇格・降格は起きずレベルの調整も要らない。
159
+ *
160
+ * 対象になるのは**カーソルが見出し行にあるとき**だけである。中身のどこにいても
161
+ * 動かせるようにすると、項目や段落を動かすつもりの操作でセクションごと動いて
162
+ * しまう。「セクションを動かすには、その見出しにカーソルを置く」を規則にする。
163
+ */
164
+ export function moveSection(direction) {
165
+ return (state, dispatch) => {
166
+ const target = targetSection(state);
167
+ if (!target)
168
+ return false;
169
+ const $target = state.doc.resolve(target.pos);
170
+ const index = $target.index();
171
+ const neighborIndex = direction === 'up' ? index - 1 : index + 1;
172
+ const neighbor = neighborIndex >= 0 && neighborIndex < $target.parent.childCount
173
+ ? $target.parent.child(neighborIndex)
174
+ : null;
175
+ // 同じ親の中に兄弟がいなければ、隣のセクションの中へ入る
176
+ if (!neighbor || neighbor.type !== n.section) {
177
+ return moveIntoSiblingSection(direction, state, dispatch);
178
+ }
179
+ if (!dispatch)
180
+ return true;
181
+ const size = target.node.nodeSize;
182
+ const insertAt = direction === 'up' ? target.pos - neighbor.nodeSize : target.pos + neighbor.nodeSize;
183
+ const tr = state.tr;
184
+ const offsetInSection = state.selection.from - target.pos;
185
+ tr.delete(target.pos, target.pos + size);
186
+ tr.insert(insertAt, target.node);
187
+ setCursor(tr, insertAt + offsetInSection);
188
+ dispatch(tr.scrollIntoView());
189
+ return true;
190
+ };
191
+ }
192
+ /**
193
+ * 親の端まで来たセクションを、親の隣のセクションの中へ入れる。
194
+ *
195
+ * 上下移動は「文書順で次(前)にある、同じ深さの置ける位置」へ進む。同じ親の中に
196
+ * 兄弟がいなければ、次に置けるのは隣のセクションの中である。下へなら子セクションの
197
+ * 先頭、上へなら末尾。深さは変わらないため、昇格・降格は起きない。
198
+ */
199
+ function moveIntoSiblingSection(direction, state, dispatch) {
200
+ const target = targetSection(state);
201
+ if (!target)
202
+ return false;
203
+ const $target = state.doc.resolve(target.pos);
204
+ const parent = $target.parent;
205
+ if (parent.type !== n.section)
206
+ return false;
207
+ const parentPos = $target.before();
208
+ const $parent = state.doc.resolve(parentPos);
209
+ const neighborIndex = direction === 'down' ? $parent.index() + 1 : $parent.index() - 1;
210
+ if (neighborIndex < 0 || neighborIndex >= $parent.parent.childCount)
211
+ return false;
212
+ const neighbor = $parent.parent.child(neighborIndex);
213
+ if (neighbor.type !== n.section)
214
+ return false;
215
+ if (!dispatch)
216
+ return true;
217
+ const neighborPos = direction === 'down' ? parentPos + parent.nodeSize : parentPos - neighbor.nodeSize;
218
+ const insertAt = direction === 'down'
219
+ ? blockContentEnd(neighbor, neighborPos)
220
+ : neighborPos + neighbor.nodeSize - 1;
221
+ const tr = state.tr;
222
+ const offsetInSection = state.selection.from - target.pos;
223
+ tr.delete(target.pos, target.pos + target.node.nodeSize);
224
+ const at = tr.mapping.map(insertAt);
225
+ tr.insert(at, target.node);
226
+ syncFrom(tr, at);
227
+ setCursor(tr, at + offsetInSection);
228
+ dispatch(tr.scrollIntoView());
229
+ return true;
230
+ }
231
+ /**
232
+ * 同じ階層の見出しをすべてリスト項目へ戻す。
233
+ *
234
+ * セクションは同じ親の中でブロックより後ろにしか置けないため、同じ階層の
235
+ * セクションは必ず末尾に連なる。その連なりをまとめて項目の列へ置き換える。
236
+ *
237
+ * **1 つだけ戻すことはしない。** 戻した項目は直前の見出しの後ろに置かれるため、
238
+ * その見出しの中身になる。兄弟だったものが子になり、書き手の作った木が変わる。
239
+ * 見出しにするときの連鎖(→ `convertToHeadings`)と同じ理由で、向きが逆になる。
240
+ */
241
+ export function dissolveLevel(state, dispatch, kind = 'bullet') {
242
+ const target = targetSection(state);
243
+ if (!target)
244
+ return false;
245
+ const $pos = state.doc.resolve(target.pos);
246
+ const parent = $pos.parent;
247
+ let index = 0;
248
+ while (index < parent.childCount && parent.child(index).type !== n.section)
249
+ index += 1;
250
+ if (index >= parent.childCount)
251
+ return false;
252
+ if (!dispatch)
253
+ return true;
254
+ const items = [];
255
+ for (let i = index; i < parent.childCount; i += 1) {
256
+ items.push(sectionToListItem(parent.child(i), kind));
257
+ }
258
+ const tr = state.tr;
259
+ if (parent.type === n.doc) {
260
+ // 文書の直下にブロックは置けない。見出しを持たないセクションへ収める。
261
+ // 置き換えるのは本文だけで、先頭のフロントマターには触れない
262
+ const start = bodyStart(state.doc);
263
+ const blocks = [];
264
+ const leading = parent.child(bodyIndex(parent));
265
+ if (leading.type === n.intro_section)
266
+ leading.forEach((child) => blocks.push(child));
267
+ const kept = blocks.reduce((total, block) => total + block.nodeSize, 0);
268
+ tr.replaceWith(start, parent.content.size, n.intro_section.createChecked(null, [...blocks, ...items]));
269
+ setCursor(tr, start + 1 + kept + 2);
270
+ }
271
+ else {
272
+ let from = $pos.start();
273
+ for (let i = 0; i < index; i += 1)
274
+ from += parent.child(i).nodeSize;
275
+ tr.replaceWith(from, $pos.end(), items);
276
+ setCursor(tr, from + 2);
277
+ }
278
+ dispatch(tr.scrollIntoView());
279
+ return true;
280
+ }
281
+ /**
282
+ * 見出しの先頭で押したとき、そのセクションを解いて、中身を 1 つ前のセクションの末尾へ移す。
283
+ *
284
+ * **ブロックの階層で結合してはいけない。** 編集基盤の既定の結合は「直前のブロック」へ
285
+ * 繋げるため、直前が箇条書きの項目だと**その項目の中へ吸い込まれる**。見出しが消える
286
+ * だけでなく、続く箇条書きまで項目の中身になる。**セクションの階層で解く。**
287
+ *
288
+ * 既定の結合に任せた場合はさらに、見出しの前にあるのが 1 つ前のセクションであるため、
289
+ * そのセクションの中へ見出しごと入る。深さが増えるぶん見出しのレベルが下がり、
290
+ * 削除キーが階層の降格として働いてしまう。
291
+ *
292
+ * タイトルを消したあとの空の見出しでは何も残らない。文字が残っていれば段落として残す
293
+ * (消える文字を作らない)。
294
+ *
295
+ * **中身と配下で行き先を分ける。** 中身は画面上の直前の行の後ろ(→ `endOfPreviousSection`)、
296
+ * 配下は**前の兄弟のセクションの子**である。同じ行き先にすると、前のセクションが配下を持つとき
297
+ * 配下がそのいちばん奥まで潜り、深さが増えて**削除キーが階層の降格として働く**。兄弟どうしは
298
+ * 同じ深さなので、前の兄弟の子にすれば配下の深さは変わらない。画面の並びも変わらない。
299
+ *
300
+ * 移す先が前書き(見出しを持たないセクション)のときだけ、**子のセクションは連れて行かない**。
301
+ * 前書きの中身はブロックだけであり、セクションを入れられないためである。
302
+ *
303
+ * 移す先が**まだ書いていない見出し**(`Enter` で足した空の見出し)のときだけ、解かずに
304
+ * その空のセクションを取り除く。解いて移すと、押した見出しのタイトルが段落になって空の
305
+ * 見出しの中へ入り(例: `#` + `# B` → `#` + `B`)、上に空の見出しがあるだけで見出しが
306
+ * 段落に化ける。空の見出しは中身を受け止める相手ではないので、繋げるかわりにその行を
307
+ * 取り除く(文書の先頭での判断と同じ → `removeEmptyLeadingBlock`)。`Enter` で足した
308
+ * 空の見出しが `Backspace` で戻り、箇条書きの空の項目と同じ往復になる。
309
+ */
310
+ export function dissolveHeadingAtStart(state, dispatch) {
311
+ const { $from, empty } = state.selection;
312
+ if (!empty || $from.parentOffset !== 0)
313
+ return false;
314
+ const heading = $from.parent;
315
+ if (heading.type !== n.heading)
316
+ return false;
317
+ const section = $from.node(-1);
318
+ if (section.type !== n.section)
319
+ return false;
320
+ // 移す先が無い(本文の先頭のセクション)。タイトルが空のときだけ、繋げるかわりに
321
+ // 行そのものを取り除く道がある(→ `removeEmptyLeadingBlock`)
322
+ if ($from.before(-1) === bodyStart(state.doc))
323
+ return false;
324
+ if (!dispatch)
325
+ return true;
326
+ const sectionPos = $from.before(-1);
327
+ const unwritten = unwrittenSectionAt(state.doc, endOfPreviousSection(state.doc, sectionPos));
328
+ if (unwritten) {
329
+ const { pos, node } = unwritten;
330
+ dispatch(state.tr.delete(pos, pos + node.nodeSize).scrollIntoView());
331
+ return true;
332
+ }
333
+ // 見出しを除いた中身。タイトルが残っていれば段落として連れて行く
334
+ const blocks = heading.content.size > 0 ? [n.paragraph.create(null, heading.content)] : [];
335
+ const children = [];
336
+ section.content.forEach((child, _offset, index) => {
337
+ if (index === 0)
338
+ return;
339
+ (child.type === n.section ? children : blocks).push(child);
340
+ });
341
+ // 前書きの中へはブロックしか入れられない。子のセクションは連れて行かず、
342
+ // もとの場所=文書の直下へ残す(親の見出しが消えるので 1 段浅くなる)
343
+ const previous = state.doc.resolve(sectionPos).nodeBefore;
344
+ const staying = previous?.type === n.intro_section ? children : [];
345
+ const moving = staying.length > 0 ? [] : children;
346
+ const target = endOfPreviousSection(state.doc, sectionPos);
347
+ // **配下の行き先は中身と分ける。** 中身が入るのは画面上の直前の行の後ろ、つまり前の
348
+ // セクションのいちばん奥である。そこへ配下まで連れて行くと**深さが増え、削除キーが
349
+ // 階層の降格として働く**(このコマンドが既定の結合を使わない理由そのもの)。
350
+ // 前の兄弟のセクションの子にすれば、兄弟どうしは同じ深さなので配下の深さが保たれる。
351
+ // 前の兄弟がセクションでなければ、もとの場所へ残す(親の見出しが消えるぶん 1 段浅くなる)
352
+ const childrenAt = previous?.type === n.section ? sectionPos - 1 : target;
353
+ const tr = state.tr;
354
+ // 配下が入るのは中身より後ろなので、配下から先に入れる(逆にすると位置がずれる)
355
+ let movedAt = childrenAt;
356
+ for (const child of moving) {
357
+ tr.insert(movedAt, child);
358
+ syncFrom(tr, movedAt);
359
+ movedAt += child.nodeSize;
360
+ }
361
+ if (blocks.length > 0)
362
+ tr.insert(target, blocks);
363
+ // 入れてから消す。入れる位置は消す位置より手前なので、位置がずれる
364
+ const from = tr.mapping.map(sectionPos);
365
+ tr.delete(from, from + section.nodeSize);
366
+ // 残した子のセクションは、消えた親のぶんだけ浅くなる。見出しのレベルも新しい深さへ合わせる
367
+ let at = from;
368
+ for (const child of staying) {
369
+ tr.insert(at, child);
370
+ syncFrom(tr, at);
371
+ at += child.nodeSize;
372
+ }
373
+ tr.setSelection(TextSelection.near(tr.doc.resolve(target)));
374
+ dispatch(tr.scrollIntoView());
375
+ return true;
376
+ }
377
+ /**
378
+ * 移す先が**まだ書いていない見出し**(タイトルも中身も持たないセクション)なら、その
379
+ * セクションを返す。移す先が中身を持つ、あるいは前にセクションが無ければ `null`。
380
+ */
381
+ function unwrittenSectionAt(doc, target) {
382
+ const $target = doc.resolve(target);
383
+ const section = $target.parent;
384
+ if (section.type !== n.section)
385
+ return null;
386
+ if (section.childCount !== 1 || section.firstChild.content.size !== 0)
387
+ return null;
388
+ return { pos: $target.before(), node: section };
389
+ }
390
+ /**
391
+ * 見出しの先頭で `Enter` を押したとき、空の見出しのセクションを上に足す。
392
+ *
393
+ * 編集基盤の既定の分割は、セクションが見出しを 1 つしか持てないため**後ろ半分を段落に
394
+ * する**。行頭で押すと、見出しが空になって中身が下の段落へ落ち、見出しが段落に化けた
395
+ * ように見える。行頭での `Enter` は分割ではなく、**同じ種別の行を上に足す**操作である。
396
+ *
397
+ * 足すのは段落ではなく**空の見出し**である。項目の先頭で押したときに空の項目が前へ入る
398
+ * のと同じで、空の見出しは「まだ書いていない見出し」であって段落に
399
+ * したいものではない。段落を足すと、入る先が前のセクションの中身になって階層が変わるうえ、
400
+ * 空の段落は書き出しに現れないため押しても何も残らない。
401
+ *
402
+ * 兄弟として入れるので、レベルは深さから決まるとおりに揃う。カーソルは見出しに残る
403
+ * (段落・項目で行頭の `Enter` を押したときと同じく、文字のある行に留まる)。
404
+ *
405
+ * 空の見出しでは働かない。行頭は行末でもあり、そこでの `Enter` は下へ続きを作る
406
+ * 既定の分割に任せる。
407
+ */
408
+ export function insertHeadingBefore(state, dispatch) {
409
+ const { $from, empty } = state.selection;
410
+ if (!empty || $from.parentOffset !== 0)
411
+ return false;
412
+ const heading = $from.parent;
413
+ if (heading.type !== n.heading || heading.content.size === 0)
414
+ return false;
415
+ if ($from.node(-1).type !== n.section)
416
+ return false;
417
+ if (!dispatch)
418
+ return true;
419
+ const added = n.section.createChecked(null, n.heading.create(heading.attrs));
420
+ dispatch(state.tr.insert($from.before(-1), added).scrollIntoView());
421
+ return true;
422
+ }
423
+ /**
424
+ * いまいるセクションの下に、空の見出しのセクションを足す(`⌘⇧Enter`)。
425
+ *
426
+ * この操作が無かったときは、`Enter` で空行を作り、見出しにして(`⌘Enter`)、段上げする
427
+ * (`Shift+Tab`)の 3 手が要った。見出し化のレベルは深さから決まるため必ず配下になり、
428
+ * 段上げで兄弟へ直すことになる。しかも**段上げは後ろの兄弟を配下へ取り込む**ので、配下を
429
+ * 持つセクションの直後に足そうとすると、もとの配下が新しいセクションの子へ移ってしまった。
430
+ *
431
+ * 取り込みは箇条書きの段上げと同じであり、同じキーが木によって違う結果を出さないための
432
+ * 仕様である(→ `liftSection`)。段上げには触れず、**足す操作を独立して持つ**。
433
+ *
434
+ * **入れる先は配下すべての後ろ**である(`nodeSize` はセクション全体を含む)。手前へ入れると
435
+ * 段上げと同じ取り込みを自分でやることになる。深さが変わらないので、レベルは今いるセクションと
436
+ * 同じであり、最下位レベルの下でも足せる(見出し化の道はそこで行き止まりになる)。
437
+ *
438
+ * **カーソルが見出し行にあるかは問わない。** 移動・複製・削除が見出し行に限っているのは、
439
+ * 対象を取り違えると丸ごと失うからである(Decision 18)。足して増えるのは空の 1 行なので、
440
+ * その理由は当たらない。前書き(見出しを持たないセクション)にいるときは、その後ろへ最上位の
441
+ * セクションを足す(`doc` は `section+` を許す)。
442
+ *
443
+ * 足すのは「まだ書いていない見出し」なので、`Backspace` で消えて元に戻る
444
+ * (→ `dissolveHeadingAtStart`)。
445
+ */
446
+ export function insertSectionAfter(state, dispatch) {
447
+ const container = enclosingContainer(state.selection.$from);
448
+ if (!container)
449
+ return false;
450
+ if (!dispatch)
451
+ return true;
452
+ // 兄弟として入れるので、レベルは入れる位置の深さから決まる
453
+ const level = state.doc.resolve(container.pos).depth + 1;
454
+ const added = n.section.createChecked(null, n.heading.create({ level }));
455
+ const at = container.pos + container.node.nodeSize;
456
+ const tr = state.tr.insert(at, added);
457
+ // セクションと見出しの 2 つを抜けた先が、足した見出しの中である
458
+ setCursor(tr, at + 2);
459
+ dispatch(tr.scrollIntoView());
460
+ return true;
461
+ }
462
+ /** カーソルを包む、もっとも内側のセクション(前書きを含む) */
463
+ function enclosingContainer($from) {
464
+ for (let depth = $from.depth; depth > 0; depth -= 1) {
465
+ const node = $from.node(depth);
466
+ if (node.type === n.section || node.type === n.intro_section) {
467
+ return { node, pos: $from.before(depth) };
468
+ }
469
+ }
470
+ return null;
471
+ }
472
+ /**
473
+ * 中身を移す先。
474
+ *
475
+ * 直前が別のセクションなら、その**いちばん奥の末尾**へ入れる。手前に置くと、ブロックは
476
+ * 子のセクションより後ろに来られないため構造が成立しない。画面の上でも、直前に見えている
477
+ * 行のすぐ後ろが移る先になる。
478
+ *
479
+ * 直前が前書きなら、その中身の末尾。子のセクションを持てないので、降りる先は 1 つしかない。
480
+ * ここで文書の直下を指すと、ブロックを置けない場所へ入れることになり、編集基盤が
481
+ * 入るように包み直して**段落が見出しへ化ける**。
482
+ */
483
+ function endOfPreviousSection(doc, sectionPos) {
484
+ const $before = doc.resolve(sectionPos);
485
+ const previous = $before.nodeBefore;
486
+ if (previous?.type === n.intro_section)
487
+ return sectionPos - 1;
488
+ if (!previous || previous.type !== n.section)
489
+ return sectionPos;
490
+ let pos = sectionPos - previous.nodeSize;
491
+ let node = previous;
492
+ for (;;) {
493
+ const last = node.lastChild;
494
+ if (!last || last.type !== n.section)
495
+ return pos + node.nodeSize - 1;
496
+ pos += 1 + node.content.size - last.nodeSize;
497
+ node = last;
498
+ }
499
+ }
500
+ /**
501
+ * 文書の先頭にある空の行を取り除く。
502
+ *
503
+ * 文書の先頭には繋げる相手がいないため、編集基盤の結合はここで何もしない。書き手から
504
+ * 見ると、後ろに内容があっても**先頭の空行だけが消せない**行き止まりになる。繋げる
505
+ * 相手がいないなら、繋げるかわりにその行を取り除く。
506
+ *
507
+ * 見出しの行を取り除くと、そのセクションは見出しを失う。中身は見出しを持たない先頭の
508
+ * セクションへ収め、子のセクションは文書の直下へ出す(→ `dissolvedSection`)。
509
+ *
510
+ * **取り除けるかどうかを場合分けしない。** 空にできないコンテナをその都度数えるかわりに、
511
+ * 「文書が空になったら空の 1 行だけの文書にする」という決まりを 1 つ置く
512
+ * (→ `keepingOneLine`)。
513
+ */
514
+ export function removeEmptyLeadingBlock(state, dispatch) {
515
+ const $cursor = emptyLeadingBlock(state);
516
+ if (!$cursor)
517
+ return false;
518
+ const container = $cursor.node(1);
519
+ const rest = container.type === n.section ? dissolvedSection(container) : withoutFirstBlock(container);
520
+ // 先頭のコンテナごと置き換える。段落を消すのも、セクションを解くのも、残りは何かという
521
+ // 1 つの問いに畳める
522
+ const start = $cursor.before(1);
523
+ const tr = state.tr;
524
+ tr.replaceWith(start, start + container.nodeSize, keepingOneLine(state.doc, rest));
525
+ // 空の 1 行しか無い文書では、取り除いた結果がもとの文書と同じになる
526
+ if (tr.doc.eq(state.doc))
527
+ return false;
528
+ if (!dispatch)
529
+ return true;
530
+ // 1 段浅くなった子のセクションは、見出しのレベルを新しい深さへ合わせ直す。
531
+ // 合わせないと、見出しの深さと段数が食い違ったまま書き出される
532
+ let at = start;
533
+ for (const moved of rest) {
534
+ if (moved.type === n.section)
535
+ syncFrom(tr, at);
536
+ at += moved.nodeSize;
537
+ }
538
+ setCursor(tr, start);
539
+ dispatch(tr.scrollIntoView());
540
+ return true;
541
+ }
542
+ /**
543
+ * カーソルが、本文のいちばん先頭にある空の段落・見出しにあるとき、その位置。
544
+ *
545
+ * 先頭であることは、コンテナの中でも本文の中でも先頭の子であることで見る。深さで絞るので、
546
+ * 1 段深いところにある箇条書きの項目は対象にならない(項目の空行は項目の側が受け持つ)。
547
+ *
548
+ * 対象を段落と見出しに限るのは、表・引用・コードブロックが**まず指してから消すもの**
549
+ * だからである(要選択の原則)。中にカーソルを置いただけで消えてよいものではない。
550
+ */
551
+ function emptyLeadingBlock(state) {
552
+ const $cursor = state.selection instanceof TextSelection ? state.selection.$cursor : null;
553
+ if (!$cursor || $cursor.depth !== 2)
554
+ return null;
555
+ if ($cursor.before(1) !== bodyStart(state.doc) || $cursor.index(1) !== 0)
556
+ return null;
557
+ if ($cursor.parent.content.size !== 0)
558
+ return null;
559
+ const type = $cursor.parent.type;
560
+ return type === n.paragraph || type === n.heading ? $cursor : null;
561
+ }
562
+ /**
563
+ * 見出しを失ったセクションを解いた残り。
564
+ *
565
+ * ブロックは見出しを持たないセクションへ収める(文書の直下にブロックは置けない)。
566
+ * 子のセクションはそのまま文書の直下のセクションになる。
567
+ */
568
+ function dissolvedSection(section) {
569
+ // 見出しの次から。セクションの中身はブロックが先、子のセクションが後ろに並ぶ
570
+ const blocks = [];
571
+ const children = [];
572
+ for (let index = 1; index < section.childCount; index += 1) {
573
+ const child = section.child(index);
574
+ (child.type === n.section ? children : blocks).push(child);
575
+ }
576
+ if (blocks.length === 0)
577
+ return children;
578
+ return [n.intro_section.createChecked(null, blocks), ...children];
579
+ }
580
+ /** 先頭のブロックを取り除いたコンテナ。中身が無くなるならコンテナも残らない */
581
+ function withoutFirstBlock(container) {
582
+ const rest = container.content.cut(container.child(0).nodeSize);
583
+ return rest.size > 0 ? [container.copy(rest)] : [];
584
+ }
585
+ /**
586
+ * 文書は 1 行以上を持つ。取り除いて何も残らないなら、空の 1 行だけの文書にする。
587
+ *
588
+ * 「消せる場面か」を数え上げるかわりに置く決まりである。空のコンテナを作れないという
589
+ * 制約は、消す側ではなく文書の側の話であり、1 か所で守れば足りる。
590
+ */
591
+ function keepingOneLine(doc, rest) {
592
+ if (rest.length > 0 || bodyCount(doc) > 1)
593
+ return rest;
594
+ return [n.intro_section.createChecked(null, n.paragraph.create())];
595
+ }
596
+ /**
597
+ * 項目・段落を見出しへ変換する。
598
+ *
599
+ * **項目のときは、その階層まるごとを見出しにする。** 1 つだけ見出しにすると、後ろに
600
+ * 並んでいた同列の項目がその見出しの中身になり、**書き手が作っていない親子関係が
601
+ * できてしまう**。マークダウンには「見出しの後に、その見出しの外側の内容」を書く構文が
602
+ * 無いため、兄弟を兄弟のまま残す書き方は「兄弟も見出しにする」以外に存在しない。
603
+ *
604
+ * 段落のときは対象をその段落だけにする。段落に「同列」という括りは無く、後ろに続く
605
+ * 内容が見出しの中身になるのは、書き手の作った木を変えることにならない。
606
+ */
607
+ export function convertToHeadings(state, dispatch) {
608
+ const origin = topLevelBlock(state);
609
+ if (!origin)
610
+ return false;
611
+ // 見出しにできるのは項目と段落だけ。表・引用・コードブロックには見出しの中身が無い
612
+ if (origin.node.type !== n.list && origin.node.type !== n.paragraph)
613
+ return false;
614
+ const level = headingLevelUnder(state.doc, origin.containerPos, origin.container);
615
+ if (level === null)
616
+ return false;
617
+ const wholeLevel = origin.node.type === n.list;
618
+ const startIndex = wholeLevel ? firstItemIndex(origin.container) : origin.index;
619
+ if (startIndex === null)
620
+ return false;
621
+ if (!dispatch)
622
+ return true;
623
+ const { container, containerPos } = origin;
624
+ const contentStart = containerPos + 1;
625
+ let regionStart = contentStart;
626
+ for (let i = 0; i < startIndex; i += 1)
627
+ regionStart += container.child(i).nodeSize;
628
+ const sections = buildSections(container, startIndex, level, wholeLevel);
629
+ if (sections.length === 0)
630
+ return false;
631
+ const tr = state.tr;
632
+ if (container.type === n.intro_section) {
633
+ // 見出しなしセクションはその位置で分割し、新しいセクションを文書の直下へ出す
634
+ const from = startIndex === 0 ? containerPos : regionStart;
635
+ tr.replaceWith(from, containerPos + container.nodeSize, sections);
636
+ }
637
+ else {
638
+ tr.replaceWith(regionStart, blockContentEnd(container, containerPos), sections);
639
+ }
640
+ // 新しい見出しの中へカーソルを置く
641
+ setCursor(tr, (container.type === n.intro_section && startIndex === 0 ? containerPos : regionStart) + 2);
642
+ dispatch(tr.scrollIntoView());
643
+ return true;
644
+ }
645
+ /**
646
+ * 対象の位置以降の内容を、見出しをともなうセクションの列へ組み替える。
647
+ * `wholeLevel` が真なら、後ろに続く同列の項目もそれぞれ見出しにする。
648
+ */
649
+ function buildSections(container, startIndex, level, wholeLevel) {
650
+ const sections = [];
651
+ let heading = null;
652
+ let content = [];
653
+ const flush = () => {
654
+ if (heading)
655
+ sections.push(n.section.createChecked(null, [heading, ...content]));
656
+ heading = null;
657
+ content = [];
658
+ };
659
+ for (let i = startIndex; i < container.childCount; i += 1) {
660
+ const child = container.child(i);
661
+ if (child.type === n.section)
662
+ break;
663
+ const startsSection = i === startIndex || (wholeLevel && child.type === n.list);
664
+ if (startsSection) {
665
+ flush();
666
+ if (child.type === n.list) {
667
+ heading = n.heading.createChecked({ level }, child.child(0).content);
668
+ // 配下の項目は 1 段繰り上がって新しい見出しの中身になる
669
+ for (let k = 1; k < child.childCount; k += 1)
670
+ content.push(child.child(k));
671
+ }
672
+ else {
673
+ heading = n.heading.createChecked({ level }, child.content);
674
+ }
675
+ }
676
+ else {
677
+ content.push(child);
678
+ }
679
+ }
680
+ flush();
681
+ return sections;
682
+ }
683
+ // --- 並びを歩く照会(`list.ts` と `block.ts` が横に参照する) ---
684
+ /** ブロックの連なりが始まる位置。セクションは先頭が見出しなので 1 から */
685
+ export function blockRunStart(container) {
686
+ return container.type === n.section ? 1 : 0;
687
+ }
688
+ /** ブロックの連なりが終わる位置(最初の子セクションのインデックス) */
689
+ export function blockRunEnd(container) {
690
+ let index = 0;
691
+ while (index < container.childCount && container.child(index).type !== n.section)
692
+ index += 1;
693
+ return index;
694
+ }
695
+ /**
696
+ * 文書順で次に来るセクション。
697
+ *
698
+ * 子セクションがあればそれが次であり、なければ後ろの兄弟を親へさかのぼって探す。
699
+ * 上へ向かう `previousContainer` とちょうど逆をたどるため、同じキーで往復できる。
700
+ */
701
+ export function nextSection(doc, container, containerPos) {
702
+ const firstChildSection = blockRunEnd(container);
703
+ if (firstChildSection < container.childCount) {
704
+ return {
705
+ node: container.child(firstChildSection),
706
+ pos: blockContentEnd(container, containerPos)
707
+ };
708
+ }
709
+ let $pos = doc.resolve(containerPos);
710
+ for (;;) {
711
+ const index = $pos.index();
712
+ if (index + 1 < $pos.parent.childCount) {
713
+ const next = $pos.parent.child(index + 1);
714
+ if (next.type === n.section) {
715
+ return { node: next, pos: $pos.pos + $pos.parent.child(index).nodeSize };
716
+ }
717
+ }
718
+ if ($pos.depth === 0)
719
+ return null;
720
+ $pos = doc.resolve($pos.before());
721
+ }
722
+ }
723
+ /**
724
+ * 文書順で前に来るセクション。
725
+ *
726
+ * 直前に兄弟セクションがあれば、その最も奥の末尾まで降りる。無ければ親セクションの
727
+ * 中身の末尾であり、これが**子セクションから親へ出る経路**になる。
728
+ */
729
+ export function previousContainer(doc, containerPos) {
730
+ const $pos = doc.resolve(containerPos);
731
+ const index = $pos.index();
732
+ if (index > 0) {
733
+ const previous = $pos.parent.child(index - 1);
734
+ if (previous.type === n.section || previous.type === n.intro_section) {
735
+ return deepestLastSection(previous, containerPos - previous.nodeSize);
736
+ }
737
+ }
738
+ // 直前がブロック、または自分が先頭 → 親の中身の末尾へ出る
739
+ if ($pos.depth === 0 || $pos.parent.type !== n.section)
740
+ return null;
741
+ return { node: $pos.parent, pos: $pos.before() };
742
+ }
743
+ /** 末尾の子セクションをたどって、最も奥のセクションまで降りる */
744
+ export function deepestLastSection(section, pos) {
745
+ let node = section;
746
+ let at = pos;
747
+ for (;;) {
748
+ const last = node.child(node.childCount - 1);
749
+ if (last.type !== n.section)
750
+ return { node, pos: at };
751
+ at = at + node.nodeSize - 1 - last.nodeSize;
752
+ node = last;
753
+ }
754
+ }
755
+ // --- 文書構造の照会(対象別ファイルが横に参照する) ---
756
+ /**
757
+ * カーソルが属する、セクション直下のブロック。
758
+ * ネストしたリスト項目は対象にしない(親から切り離されて構造の意味が失われるため)。
759
+ *
760
+ * **種別で絞らない。** 表・引用・コードブロックも、段落と同じくセクション直下のブロックで
761
+ * ある。絞っていたときは、それらにカーソルを置くと複製も削除も何も起きなかった。
762
+ * 種別に条件がある呼び出し側は、受け取ってから自分で確かめる。
763
+ */
764
+ export function topLevelBlock(state) {
765
+ const $from = state.selection.$from;
766
+ if ($from.parent.type === n.heading)
767
+ return null;
768
+ for (let depth = $from.depth; depth > 0; depth -= 1) {
769
+ const container = $from.node(depth - 1);
770
+ if (container.type !== n.section && container.type !== n.intro_section)
771
+ continue;
772
+ const node = $from.node(depth);
773
+ // カーソルがより内側の項目にあるなら、ネストした項目を対象にしている
774
+ if (depth < innermostListDepth($from, depth))
775
+ return null;
776
+ return {
777
+ container,
778
+ containerPos: depth - 1 === 0 ? $from.before(depth) - 1 : $from.before(depth - 1),
779
+ index: $from.index(depth - 1),
780
+ pos: $from.before(depth),
781
+ node
782
+ };
783
+ }
784
+ return null;
785
+ }
786
+ /** カーソルをもっとも内側で包むリスト項目の深さ(なければ `fallback`) */
787
+ function innermostListDepth($from, fallback) {
788
+ for (let depth = $from.depth; depth > 0; depth -= 1) {
789
+ if ($from.node(depth).type === n.list)
790
+ return depth;
791
+ }
792
+ return fallback;
793
+ }
794
+ /** コンテナの中に置く見出しのレベル。最下位を超える場合は `null` */
795
+ function headingLevelUnder(doc, containerPos, container) {
796
+ if (container.type === n.intro_section)
797
+ return 1;
798
+ const level = doc.resolve(containerPos).depth + 2;
799
+ return level > MAX_HEADING_LEVEL ? null : level;
800
+ }
801
+ /** コンテナの中で最初に現れるリスト項目の位置(なければ `null`) */
802
+ function firstItemIndex(container) {
803
+ for (let i = 0; i < container.childCount; i += 1) {
804
+ if (container.child(i).type === n.list)
805
+ return i;
806
+ }
807
+ return null;
808
+ }
809
+ /** ブロックの並びが終わる位置(最初の子セクションの手前) */
810
+ export function blockContentEnd(container, containerPos) {
811
+ let end = containerPos + 1;
812
+ for (let i = 0; i < container.childCount; i += 1) {
813
+ const child = container.child(i);
814
+ if (child.type === n.section)
815
+ break;
816
+ end += child.nodeSize;
817
+ }
818
+ return end;
819
+ }
820
+ /**
821
+ * 階層操作の対象となるセクション。
822
+ * カーソルが見出し行にあるときだけ対象になる(段落・リスト項目・見出しなしセクションは対象外)。
823
+ */
824
+ export function targetSection(state) {
825
+ const $from = state.selection.$from;
826
+ if ($from.parent.type !== n.heading)
827
+ return null;
828
+ const ref = sectionTree.resolveSection(state.doc, $from.pos);
829
+ if (!ref || ref.level === null)
830
+ return null;
831
+ return ref;
832
+ }
833
+ export function previousSiblingSection(doc, pos) {
834
+ const $pos = doc.resolve(pos);
835
+ const index = $pos.index();
836
+ if (index === 0)
837
+ return null;
838
+ const previous = $pos.parent.child(index - 1);
839
+ if (previous.type !== n.section)
840
+ return null;
841
+ return { node: previous, pos: pos - previous.nodeSize };
842
+ }
843
+ /** 対象の中でもっとも深い見出しのレベル(深くできるかの判定に使う) */
844
+ function deepestLevelIn(section, baseLevel) {
845
+ let deepest = baseLevel;
846
+ const walk = (node, level) => {
847
+ node.forEach((child) => {
848
+ if (child.type !== n.section)
849
+ return;
850
+ deepest = Math.max(deepest, level + 1);
851
+ walk(child, level + 1);
852
+ });
853
+ };
854
+ walk(section, baseLevel);
855
+ return deepest;
856
+ }
857
+ /** セクションを項目へ組み替える。子セクションは入れ子の項目になる */
858
+ export function sectionToListItem(section, kind) {
859
+ const content = [n.paragraph.createChecked(null, section.child(0).content)];
860
+ for (let i = 1; i < section.childCount; i += 1) {
861
+ const child = section.child(i);
862
+ content.push(child.type === n.section ? sectionToListItem(child, kind) : child);
863
+ }
864
+ return n.list.createChecked({ kind }, content);
865
+ }