@14ch/svelte-md-outliner 0.0.28 → 0.0.30

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.
@@ -0,0 +1,54 @@
1
+ /**
2
+ * 言語を選ぶ Select に並べる言語。並びは表示名の順で、`mermaid` もほかと同じ並びに入る。
3
+ *
4
+ * 正式な名前は、マークダウンで最もよく使われる綴りにする。書き出した文書は他のツール
5
+ * (GitHub など)でも読まれるため、ハイライトのライブラリの都合の名前(`html` に対する
6
+ * `markup` など)は書かない。
7
+ */
8
+ export const CODE_LANGUAGES = [
9
+ { id: 'c', label: 'C', aliases: ['h'] },
10
+ { id: 'csharp', label: 'C#', aliases: ['cs', 'c#'] },
11
+ { id: 'cpp', label: 'C++', aliases: ['c++', 'cc', 'hpp'] },
12
+ { id: 'css', label: 'CSS', aliases: [] },
13
+ { id: 'diff', label: 'Diff', aliases: ['patch'] },
14
+ { id: 'dockerfile', label: 'Dockerfile', aliases: ['docker'] },
15
+ { id: 'go', label: 'Go', aliases: ['golang'] },
16
+ { id: 'graphql', label: 'GraphQL', aliases: ['gql'] },
17
+ { id: 'html', label: 'HTML', aliases: ['htm'] },
18
+ { id: 'java', label: 'Java', aliases: [] },
19
+ { id: 'javascript', label: 'JavaScript', aliases: ['js', 'mjs', 'cjs'] },
20
+ { id: 'json', label: 'JSON', aliases: ['jsonc'] },
21
+ { id: 'jsx', label: 'JSX', aliases: [] },
22
+ { id: 'kotlin', label: 'Kotlin', aliases: ['kt', 'kts'] },
23
+ { id: 'markdown', label: 'Markdown', aliases: ['md'] },
24
+ { id: 'mermaid', label: 'Mermaid', aliases: [] },
25
+ { id: 'php', label: 'PHP', aliases: [] },
26
+ { id: 'python', label: 'Python', aliases: ['py'] },
27
+ { id: 'ruby', label: 'Ruby', aliases: ['rb'] },
28
+ { id: 'rust', label: 'Rust', aliases: ['rs'] },
29
+ { id: 'scss', label: 'SCSS', aliases: [] },
30
+ { id: 'bash', label: 'Shell', aliases: ['sh', 'shell', 'zsh'] },
31
+ { id: 'sql', label: 'SQL', aliases: [] },
32
+ { id: 'swift', label: 'Swift', aliases: [] },
33
+ { id: 'toml', label: 'TOML', aliases: [] },
34
+ { id: 'tsx', label: 'TSX', aliases: [] },
35
+ { id: 'typescript', label: 'TypeScript', aliases: ['ts', 'mts', 'cts'] },
36
+ { id: 'xml', label: 'XML', aliases: ['svg'] },
37
+ { id: 'yaml', label: 'YAML', aliases: ['yml'] }
38
+ ];
39
+ /** 言語名から一覧の言語を探す。正式な名前と別名の両方を見て、大文字・小文字は区別しない */
40
+ export function findCodeLanguage(name) {
41
+ const key = name.toLowerCase();
42
+ return (CODE_LANGUAGES.find((language) => language.id === key || language.aliases.includes(key)) ?? null);
43
+ }
44
+ /**
45
+ * 言語名から、作るノードの種類を決める。読み込み・` ``` ` からの入力・Select の 3 つが
46
+ * これを使い、同じ言語名から違うブロックができないようにする。
47
+ *
48
+ * **小文字の `mermaid` だけを図のブロックにする。** 書き出しは常に `mermaid` を出すため、
49
+ * `Mermaid` などを図にすると、書き出して読み直したときに綴りが変わる。
50
+ * 別名を正式な名前に直さないのも同じ理由で、読み込んだだけで綴りを変えない。
51
+ */
52
+ export function codeBlockNodeFor(language) {
53
+ return language === 'mermaid' ? { type: 'mermaid_block' } : { type: 'code_block', language };
54
+ }
@@ -32,3 +32,19 @@ export interface SectionRef {
32
32
  export type BlockKind = 'heading' | 'paragraph' | 'bullet_list' | 'ordered_list' | 'task_list' | 'blockquote' | 'code_block';
33
33
  /** 表の列の配置指定。`schema.ts` の `cellAttributes.align` が取る値 */
34
34
  export type CellAlign = 'left' | 'center' | 'right' | null;
35
+ /** 言語の一覧に載せる言語の正式な名前。Select で選んだときにマークダウンへ書く名前 */
36
+ export type CodeLanguageId = 'bash' | 'c' | 'cpp' | 'csharp' | 'css' | 'diff' | 'dockerfile' | 'go' | 'graphql' | 'html' | 'java' | 'javascript' | 'json' | 'jsx' | 'kotlin' | 'markdown' | 'mermaid' | 'php' | 'python' | 'ruby' | 'rust' | 'scss' | 'sql' | 'swift' | 'toml' | 'tsx' | 'typescript' | 'xml' | 'yaml';
37
+ export interface CodeLanguage {
38
+ readonly id: CodeLanguageId;
39
+ /** 書き手が読む名前(`TypeScript`・`Shell`) */
40
+ readonly label: string;
41
+ /** マークダウンに書かれうる別名(`ts`・`sh`)。小文字で持つ */
42
+ readonly aliases: readonly string[];
43
+ }
44
+ /** 言語名から決まる、作るノードの種類 */
45
+ export type CodeBlockNode = {
46
+ readonly type: 'mermaid_block';
47
+ } | {
48
+ readonly type: 'code_block';
49
+ readonly language: string;
50
+ };
@@ -1,5 +1,6 @@
1
1
  import { Fragment, Mark } from 'prosemirror-model';
2
2
  import { MAX_HEADING_LEVEL } from '../document/document.types.js';
3
+ import { codeBlockNodeFor } from '../document/codeLanguage.js';
3
4
  import { canBeItemLine, outlineSchema } from '../document/schema.js';
4
5
  import { splitFrontMatter } from './frontMatter.js';
5
6
  import { markdownIt } from './markdownIt.js';
@@ -133,13 +134,12 @@ function readBlock(tokens, start) {
133
134
  // 開き直すたびに戻る)。空行を書いた形(`\n\n`)は 1 つだけ落として保つ
134
135
  const text = token.content.replace(/\n$/, '');
135
136
  const content = text ? outlineSchema.text(text) : null;
136
- // 書き出しは常に `mermaid` を出すため、表記ゆれ(`Mermaid` 等)を取り込むと
137
- // 往復でフェンスの文字が変わる。小文字完全一致だけを専用ブロックにする
137
+ const block = codeBlockNodeFor(language);
138
138
  return {
139
139
  nodes: [
140
- language === 'mermaid'
140
+ block.type === 'mermaid_block'
141
141
  ? n.mermaid_block.createChecked(null, content)
142
- : n.code_block.createChecked({ language }, content)
142
+ : n.code_block.createChecked({ language: block.language }, content)
143
143
  ],
144
144
  next: start + 1
145
145
  };
@@ -5,3 +5,12 @@ export declare function isInCodeBlock(state: EditorState): boolean;
5
5
  /** コードブロックの中では階層操作ではなく字下げとして扱う */
6
6
  export declare const indentInCodeBlock: EditorCommand;
7
7
  export declare const outdentInCodeBlock: EditorCommand;
8
+ /**
9
+ * pos にあるコードブロックの言語を language にする。どのノードになるかは
10
+ * `codeBlockNodeFor` が決めるので、`mermaid` を選べば図のブロックになり、図のブロックで
11
+ * 別の言語を選べば普通のコードブロックに戻る。
12
+ *
13
+ * ノードの種類と属性だけを入れ替え、中身の文字・位置・深さは変えない。どちらの種類も
14
+ * 中身は文字だけで書式を持たないため、入れ替えは常に成り立つ。
15
+ */
16
+ export declare function setCodeBlockLanguage(pos: number, language: string): EditorCommand;
@@ -1,3 +1,6 @@
1
+ import { codeBlockNodeFor } from '../../models/document/codeLanguage.js';
2
+ import { outlineSchema } from '../../models/document/schema.js';
3
+ const n = outlineSchema.nodes;
1
4
  /** カーソルがコードブロックの文字の中にあるか。字下げの分岐と同じ判定を 1 つにする */
2
5
  export function isInCodeBlock(state) {
3
6
  return state.selection.$from.parent.type.spec.code === true;
@@ -24,3 +27,25 @@ export const outdentInCodeBlock = (state, dispatch) => {
24
27
  dispatch(state.tr.delete(from, from + leading[0].length).scrollIntoView());
25
28
  return true;
26
29
  };
30
+ /**
31
+ * pos にあるコードブロックの言語を language にする。どのノードになるかは
32
+ * `codeBlockNodeFor` が決めるので、`mermaid` を選べば図のブロックになり、図のブロックで
33
+ * 別の言語を選べば普通のコードブロックに戻る。
34
+ *
35
+ * ノードの種類と属性だけを入れ替え、中身の文字・位置・深さは変えない。どちらの種類も
36
+ * 中身は文字だけで書式を持たないため、入れ替えは常に成り立つ。
37
+ */
38
+ export function setCodeBlockLanguage(pos, language) {
39
+ return (state, dispatch) => {
40
+ const node = state.doc.nodeAt(pos);
41
+ if (!node || (node.type !== n.code_block && node.type !== n.mermaid_block))
42
+ return false;
43
+ const block = codeBlockNodeFor(language);
44
+ if (dispatch) {
45
+ dispatch(block.type === 'mermaid_block'
46
+ ? state.tr.setNodeMarkup(pos, n.mermaid_block)
47
+ : state.tr.setNodeMarkup(pos, n.code_block, { language: block.language }));
48
+ }
49
+ return true;
50
+ };
51
+ }
@@ -1,10 +1,7 @@
1
1
  import type { EditorCommand } from '../operations.types';
2
2
  /**
3
- * フェンスの記法が作るブロックにする。
4
- *
5
- * **完全一致の `mermaid` だけが図のブロック**で、それ以外は言語名を持つコードブロックに
6
- * なる。この振り分けは読み込み(→ `parser.ts`)と同じであり、記法から行き先を決める
7
- * 判断を 2 つに分けない。
3
+ * ` ``` ` の記法が作るブロックにする。どのノードになるかは `codeBlockNodeFor` が決め、
4
+ * 読み込み(→ `parser.ts`)と同じ結果になる。
8
5
  *
9
6
  * 項目の行で打たれたときに項目を解くのは `changeLine` の役目である。フェンスのブロックは
10
7
  * 項目の行になれない(→ `parser.ts` の `withOwnLine`)ため、項目を残すと「中黒の付いた
@@ -1,4 +1,5 @@
1
1
  import { setBlockType } from 'prosemirror-commands';
2
+ import { codeBlockNodeFor } from '../../models/document/codeLanguage.js';
2
3
  import { outlineSchema } from '../../models/document/schema.js';
3
4
  import { changeLine, convertFromMarkup } from './block.js';
4
5
  const n = outlineSchema.nodes;
@@ -8,20 +9,18 @@ const n = outlineSchema.nodes;
8
9
  */
9
10
  const FENCE = /^```([a-zA-Z0-9_+#-]*)$/;
10
11
  /**
11
- * フェンスの記法が作るブロックにする。
12
- *
13
- * **完全一致の `mermaid` だけが図のブロック**で、それ以外は言語名を持つコードブロックに
14
- * なる。この振り分けは読み込み(→ `parser.ts`)と同じであり、記法から行き先を決める
15
- * 判断を 2 つに分けない。
12
+ * ` ``` ` の記法が作るブロックにする。どのノードになるかは `codeBlockNodeFor` が決め、
13
+ * 読み込み(→ `parser.ts`)と同じ結果になる。
16
14
  *
17
15
  * 項目の行で打たれたときに項目を解くのは `changeLine` の役目である。フェンスのブロックは
18
16
  * 項目の行になれない(→ `parser.ts` の `withOwnLine`)ため、項目を残すと「中黒の付いた
19
17
  * コードブロック」になり、読み直したときに項目の行が 1 つ増える。
20
18
  */
21
19
  export function toFencedBlock(language) {
22
- return changeLine(language === 'mermaid'
20
+ const block = codeBlockNodeFor(language);
21
+ return changeLine(block.type === 'mermaid_block'
23
22
  ? setBlockType(n.mermaid_block)
24
- : setBlockType(n.code_block, { language }));
23
+ : setBlockType(n.code_block, { language: block.language }));
25
24
  }
26
25
  /**
27
26
  * 行頭からの ` ``` `(+言語名)に続く改行で、フェンスのブロックを作る。
@@ -122,6 +122,13 @@ export interface LinkRange {
122
122
  readonly from: number;
123
123
  readonly to: number;
124
124
  }
125
+ /** 選択されているコードブロック(カーソルが中にある、またはブロック全体が選択されている) */
126
+ export interface SelectedCodeBlock {
127
+ /** ブロックの開始位置 */
128
+ readonly pos: number;
129
+ /** ブロックの言語名。`mermaid_block` は `mermaid` */
130
+ readonly language: string;
131
+ }
125
132
  /** 同じリンクが続く区間。書式が混ざって文字の節が分かれていても 1 つに数える */
126
133
  export interface LinkRun extends LinkRange {
127
134
  readonly href: string;
@@ -0,0 +1,29 @@
1
+ import type { Root } from 'hast';
2
+ import { Plugin } from 'prosemirror-state';
3
+ import { DecorationSet } from 'prosemirror-view';
4
+ import type { CodeLanguageId } from '../../models/document/document.types';
5
+ /** 言語の文法を読み込んで登録する。失敗したら、次に呼ばれたときに読み直す */
6
+ export declare function loadCodeGrammar(id: CodeLanguageId): Promise<void>;
7
+ /** 読み込み済みの言語なら、コードをトークンに分けた木を返す。まだなら null */
8
+ export declare function highlightCode(id: CodeLanguageId, code: string): Root | null;
9
+ /** テストが「import しただけでは読み込まれない」ことを確かめるための述語 */
10
+ export declare function highlighterLoadStarted(): boolean;
11
+ interface HighlightState {
12
+ readonly decorations: DecorationSet;
13
+ /** 文法がまだ読み込まれていない言語。プラグインの view が読み込みを始める */
14
+ readonly missing: readonly CodeLanguageId[];
15
+ }
16
+ /**
17
+ * コードブロック(`code_block` と `mermaid_block`)の文字に、トークンの種類ごとの class を
18
+ * decoration で付ける。文書は変えないので、書き出し・Undo・変更の通知には現れない。
19
+ *
20
+ * **かな漢字変換の最中は計算し直さない。** 変換中の文字の周りで decoration が変わると、
21
+ * 編集基盤が DOM を描き直し、変換中の文字が壊れる。変換中は前の decoration の位置だけを
22
+ * ずらして合わせ、変換が終わってから計算し直す。変換の始まりと終わりは Transaction を
23
+ * 伴わないので、プラグインのインスタンスごとの変数に持つ(→ `compositionState.ts`)。
24
+ *
25
+ * 計算の結果はブロックのノードごとに覚える。ノードは中身が変わらなければ同じ
26
+ * オブジェクトのままなので、中身か言語が変わったブロックだけ計算し直せばよい。
27
+ */
28
+ export declare function codeHighlightPlugin(): Plugin<HighlightState>;
29
+ export {};
@@ -0,0 +1,240 @@
1
+ import { Plugin, PluginKey } from 'prosemirror-state';
2
+ import { Decoration, DecorationSet } from 'prosemirror-view';
3
+ import { findCodeLanguage } from '../../models/document/codeLanguage.js';
4
+ import { outlineSchema } from '../../models/document/schema.js';
5
+ import { SETTLE_LIMIT_MS } from './compositionState.js';
6
+ /** 正式な名前ごとの文法。型によって、一覧の全言語に文法があることを保証する */
7
+ const GRAMMARS = {
8
+ bash: { name: 'bash', load: () => import('refractor/bash') },
9
+ c: { name: 'c', load: () => import('refractor/c') },
10
+ cpp: { name: 'cpp', load: () => import('refractor/cpp') },
11
+ csharp: { name: 'csharp', load: () => import('refractor/csharp') },
12
+ css: { name: 'css', load: () => import('refractor/css') },
13
+ diff: { name: 'diff', load: () => import('refractor/diff') },
14
+ dockerfile: { name: 'docker', load: () => import('refractor/docker') },
15
+ go: { name: 'go', load: () => import('refractor/go') },
16
+ graphql: { name: 'graphql', load: () => import('refractor/graphql') },
17
+ html: { name: 'markup', load: () => import('refractor/markup') },
18
+ java: { name: 'java', load: () => import('refractor/java') },
19
+ javascript: { name: 'javascript', load: () => import('refractor/javascript') },
20
+ json: { name: 'json', load: () => import('refractor/json') },
21
+ jsx: { name: 'jsx', load: () => import('refractor/jsx') },
22
+ kotlin: { name: 'kotlin', load: () => import('refractor/kotlin') },
23
+ markdown: { name: 'markdown', load: () => import('refractor/markdown') },
24
+ mermaid: { name: 'mermaid', load: () => import('refractor/mermaid') },
25
+ php: { name: 'php', load: () => import('refractor/php') },
26
+ python: { name: 'python', load: () => import('refractor/python') },
27
+ ruby: { name: 'ruby', load: () => import('refractor/ruby') },
28
+ rust: { name: 'rust', load: () => import('refractor/rust') },
29
+ scss: { name: 'scss', load: () => import('refractor/scss') },
30
+ sql: { name: 'sql', load: () => import('refractor/sql') },
31
+ swift: { name: 'swift', load: () => import('refractor/swift') },
32
+ toml: { name: 'toml', load: () => import('refractor/toml') },
33
+ tsx: { name: 'tsx', load: () => import('refractor/tsx') },
34
+ typescript: { name: 'typescript', load: () => import('refractor/typescript') },
35
+ xml: { name: 'markup', load: () => import('refractor/markup') },
36
+ yaml: { name: 'yaml', load: () => import('refractor/yaml') }
37
+ };
38
+ let coreLoading = null;
39
+ let core = null;
40
+ const grammarLoading = new Map();
41
+ const registered = new Set();
42
+ function loadCore() {
43
+ if (!coreLoading) {
44
+ coreLoading = import('refractor/core').then(({ refractor }) => (core = refractor));
45
+ coreLoading.catch(() => {
46
+ coreLoading = null;
47
+ });
48
+ }
49
+ return coreLoading;
50
+ }
51
+ /** 言語の文法を読み込んで登録する。失敗したら、次に呼ばれたときに読み直す */
52
+ export function loadCodeGrammar(id) {
53
+ let pending = grammarLoading.get(id);
54
+ if (!pending) {
55
+ const grammar = GRAMMARS[id];
56
+ pending = Promise.all([loadCore(), grammar.load()]).then(([refractor, syntax]) => {
57
+ refractor.register(syntax.default);
58
+ registered.add(id);
59
+ });
60
+ grammarLoading.set(id, pending);
61
+ pending.catch(() => grammarLoading.delete(id));
62
+ }
63
+ return pending;
64
+ }
65
+ /** 読み込み済みの言語なら、コードをトークンに分けた木を返す。まだなら null */
66
+ export function highlightCode(id, code) {
67
+ if (!core || !registered.has(id))
68
+ return null;
69
+ return core.highlight(code, GRAMMARS[id].name);
70
+ }
71
+ /** テストが「import しただけでは読み込まれない」ことを確かめるための述語 */
72
+ export function highlighterLoadStarted() {
73
+ return coreLoading !== null || grammarLoading.size > 0;
74
+ }
75
+ // --- プラグイン ---
76
+ const n = outlineSchema.nodes;
77
+ const codeHighlightKey = new PluginKey('codeHighlight');
78
+ /** 読み込みが終わった・変換が終わったときに、計算し直させる印 */
79
+ const RECOMPUTE_META = 'recompute';
80
+ /**
81
+ * コードブロック(`code_block` と `mermaid_block`)の文字に、トークンの種類ごとの class を
82
+ * decoration で付ける。文書は変えないので、書き出し・Undo・変更の通知には現れない。
83
+ *
84
+ * **かな漢字変換の最中は計算し直さない。** 変換中の文字の周りで decoration が変わると、
85
+ * 編集基盤が DOM を描き直し、変換中の文字が壊れる。変換中は前の decoration の位置だけを
86
+ * ずらして合わせ、変換が終わってから計算し直す。変換の始まりと終わりは Transaction を
87
+ * 伴わないので、プラグインのインスタンスごとの変数に持つ(→ `compositionState.ts`)。
88
+ *
89
+ * 計算の結果はブロックのノードごとに覚える。ノードは中身が変わらなければ同じ
90
+ * オブジェクトのままなので、中身か言語が変わったブロックだけ計算し直せばよい。
91
+ */
92
+ export function codeHighlightPlugin() {
93
+ const cache = new WeakMap();
94
+ let composing = false;
95
+ /** 変換中に位置だけ合わせたので、計算し直しが要る */
96
+ let stale = false;
97
+ let settle = null;
98
+ return new Plugin({
99
+ key: codeHighlightKey,
100
+ state: {
101
+ init: (_, state) => highlight(state.doc, cache),
102
+ apply: (tr, value) => {
103
+ if (composing) {
104
+ if (tr.docChanged)
105
+ stale = true;
106
+ return { ...value, decorations: value.decorations.map(tr.mapping, tr.doc) };
107
+ }
108
+ if (!tr.docChanged && !tr.getMeta(codeHighlightKey))
109
+ return value;
110
+ stale = false;
111
+ return highlight(tr.doc, cache);
112
+ }
113
+ },
114
+ props: {
115
+ decorations: (state) => codeHighlightKey.getState(state).decorations,
116
+ handleDOMEvents: {
117
+ compositionstart: () => {
118
+ composing = true;
119
+ if (settle !== null)
120
+ clearTimeout(settle);
121
+ return false;
122
+ },
123
+ /**
124
+ * 確定した文字はまだ文書に入っていない。入るときの Transaction で計算し直すが、
125
+ * 来ないこともあるので、上限を過ぎたら自分で計算し直させる
126
+ */
127
+ compositionend: (view) => {
128
+ composing = false;
129
+ settle = setTimeout(() => {
130
+ settle = null;
131
+ if (stale && !view.isDestroyed) {
132
+ view.dispatch(view.state.tr.setMeta(codeHighlightKey, RECOMPUTE_META));
133
+ }
134
+ }, SETTLE_LIMIT_MS);
135
+ return false;
136
+ }
137
+ }
138
+ },
139
+ view: (view) => {
140
+ /** 読み込み中の言語。同じ言語の読み込みに、計算し直しを何度も結びつけない */
141
+ const loading = new Set();
142
+ const load = () => {
143
+ for (const id of codeHighlightKey.getState(view.state).missing) {
144
+ if (loading.has(id))
145
+ continue;
146
+ loading.add(id);
147
+ loadCodeGrammar(id)
148
+ .then(() => {
149
+ if (!view.isDestroyed) {
150
+ view.dispatch(view.state.tr.setMeta(codeHighlightKey, RECOMPUTE_META));
151
+ }
152
+ },
153
+ // 失敗したブロックは 1 色のまま。次に状態が変わったときに読み直す
154
+ () => { })
155
+ .finally(() => loading.delete(id));
156
+ }
157
+ };
158
+ load();
159
+ return {
160
+ update: load,
161
+ destroy: () => {
162
+ if (settle !== null)
163
+ clearTimeout(settle);
164
+ }
165
+ };
166
+ }
167
+ });
168
+ }
169
+ /** 文書の中のコードブロックを色分けする。文法の無い言語は読み込み待ちとして返す */
170
+ function highlight(doc, cache) {
171
+ const decorations = [];
172
+ const missing = new Set();
173
+ doc.descendants((node, pos) => {
174
+ if (node.type !== n.code_block && node.type !== n.mermaid_block)
175
+ return !node.isTextblock;
176
+ const language = findCodeLanguage(node.type === n.mermaid_block ? 'mermaid' : String(node.attrs.language));
177
+ if (!language)
178
+ return false;
179
+ let ranges = cache.get(node);
180
+ if (!ranges) {
181
+ const root = highlightCode(language.id, node.textContent);
182
+ if (!root) {
183
+ missing.add(language.id);
184
+ return false;
185
+ }
186
+ ranges = tokenRanges(root);
187
+ cache.set(node, ranges);
188
+ }
189
+ const start = pos + 1;
190
+ for (const range of ranges) {
191
+ decorations.push(Decoration.inline(start + range.from, start + range.to, { class: range.class }));
192
+ }
193
+ return false;
194
+ });
195
+ return {
196
+ decorations: DecorationSet.create(doc, decorations),
197
+ missing: [...missing]
198
+ };
199
+ }
200
+ /**
201
+ * トークンの木から、トークンごとの範囲と class を作る。**文字は長さを数えるだけで、
202
+ * DOM へは書かない**(コードの中の HTML が要素として描かれないように)。
203
+ *
204
+ * class はライブラリの種類の名前から作り、ライブラリの `token` は付けない。置いた先の
205
+ * ページに Prism の CSS があっても、エディタの中に効かないようにするためである。
206
+ */
207
+ function tokenRanges(root) {
208
+ const ranges = [];
209
+ const walk = (children, from) => {
210
+ let offset = from;
211
+ for (const child of children) {
212
+ if (child.type === 'text') {
213
+ offset += child.value.length;
214
+ }
215
+ else if (child.type === 'element') {
216
+ const start = offset;
217
+ offset = walk(child.children, offset);
218
+ const types = classNames(child.properties.className).filter((name) => name !== 'token');
219
+ if (types.length > 0 && offset > start) {
220
+ ranges.push({
221
+ from: start,
222
+ to: offset,
223
+ class: [
224
+ 'markdown-editor__code-token',
225
+ ...types.map((type) => `markdown-editor__code-token--${type}`)
226
+ ].join(' ')
227
+ });
228
+ }
229
+ }
230
+ }
231
+ return offset;
232
+ };
233
+ walk(root.children, 0);
234
+ return ranges;
235
+ }
236
+ function classNames(value) {
237
+ if (Array.isArray(value))
238
+ return value.map(String);
239
+ return typeof value === 'string' ? value.split(/\s+/) : [];
240
+ }
@@ -0,0 +1,16 @@
1
+ import { Plugin } from 'prosemirror-state';
2
+ import type { SelectedCodeBlock } from '../operations.types';
3
+ /**
4
+ * 選択されているコードブロックと、編集エリアにフォーカスがあるかを求め、**どちらかが
5
+ * 変わったときだけ**知らせる。表示は持たない(→ `CodeLanguagePopover`)。
6
+ *
7
+ * ブロックの中で文字を打っているだけなら、どちらも変わらないので知らせない。
8
+ *
9
+ * 選択されているブロックは、フォーカスの有無と関係なく求める。フォーカスが外れても
10
+ * 選択はエディタの状態に残っているので、フォーカスが言語の Select にあるあいだに言語を
11
+ * 変えても、新しい言語名が届く。出すかどうかは受け取る側が決める。
12
+ *
13
+ * かな漢字変換の最中は知らせない。始まりは `compositionstart` で受ける(`view.composing`
14
+ * だけでは、変換の始まりの描き直しに間に合わない。→ `selectionToolbar.ts`)。
15
+ */
16
+ export declare function codeLanguagePopoverPlugin(onChange: (block: SelectedCodeBlock | null, editorFocused: boolean) => void): Plugin;
@@ -0,0 +1,73 @@
1
+ import { NodeSelection, Plugin } from 'prosemirror-state';
2
+ import { outlineSchema } from '../../models/document/schema.js';
3
+ import { isEditorFocused } from './editorFocus.js';
4
+ const n = outlineSchema.nodes;
5
+ /**
6
+ * 選択されているコードブロックと、編集エリアにフォーカスがあるかを求め、**どちらかが
7
+ * 変わったときだけ**知らせる。表示は持たない(→ `CodeLanguagePopover`)。
8
+ *
9
+ * ブロックの中で文字を打っているだけなら、どちらも変わらないので知らせない。
10
+ *
11
+ * 選択されているブロックは、フォーカスの有無と関係なく求める。フォーカスが外れても
12
+ * 選択はエディタの状態に残っているので、フォーカスが言語の Select にあるあいだに言語を
13
+ * 変えても、新しい言語名が届く。出すかどうかは受け取る側が決める。
14
+ *
15
+ * かな漢字変換の最中は知らせない。始まりは `compositionstart` で受ける(`view.composing`
16
+ * だけでは、変換の始まりの描き直しに間に合わない。→ `selectionToolbar.ts`)。
17
+ */
18
+ export function codeLanguagePopoverPlugin(onChange) {
19
+ let composing = false;
20
+ let last = null;
21
+ const notify = (view) => {
22
+ if (composing)
23
+ return;
24
+ const block = view.editable ? selectedCodeBlock(view.state) : null;
25
+ const editorFocused = isEditorFocused(view.state);
26
+ if (last && sameBlock(last.block, block) && last.editorFocused === editorFocused)
27
+ return;
28
+ last = { block, editorFocused };
29
+ onChange(block, editorFocused);
30
+ };
31
+ return new Plugin({
32
+ props: {
33
+ handleDOMEvents: {
34
+ compositionstart: () => {
35
+ composing = true;
36
+ return false;
37
+ },
38
+ compositionend: (view) => {
39
+ composing = false;
40
+ notify(view);
41
+ return false;
42
+ }
43
+ }
44
+ },
45
+ view: (view) => {
46
+ notify(view);
47
+ return {
48
+ update: notify,
49
+ destroy: () => onChange(null, false)
50
+ };
51
+ }
52
+ });
53
+ }
54
+ function selectedCodeBlock(state) {
55
+ const { selection } = state;
56
+ if (selection instanceof NodeSelection) {
57
+ return codeBlockAt(selection.node.type, selection.from, selection.node.attrs.language);
58
+ }
59
+ const { $from, $to } = selection;
60
+ if (!$from.sameParent($to) || $from.depth === 0)
61
+ return null;
62
+ return codeBlockAt($from.parent.type, $from.before(), $from.parent.attrs.language);
63
+ }
64
+ function codeBlockAt(type, pos, language) {
65
+ if (type === n.mermaid_block)
66
+ return { pos, language: 'mermaid' };
67
+ if (type === n.code_block)
68
+ return { pos, language: String(language) };
69
+ return null;
70
+ }
71
+ function sameBlock(a, b) {
72
+ return a === b || (a !== null && b !== null && a.pos === b.pos && a.language === b.language);
73
+ }
@@ -0,0 +1,42 @@
1
+ import type { SelectedCodeBlock } from '../operations/operations.types';
2
+ import type { EditorExtension, EditorSession } from './editorSession.types';
3
+ export interface CodeLanguagePopoverControllerOptions {
4
+ /** 現在のセッション。生き死にの管理はコンポーネントが持つ */
5
+ readonly getSession: () => EditorSession | null;
6
+ /** 言語を指定しない選択肢の表示。呼ぶ時点の文言を読む */
7
+ readonly getNoneLabel: () => string;
8
+ }
9
+ export interface CodeLanguageOption {
10
+ readonly label: string;
11
+ /** 正式な名前。「なし」は ''。一覧に無い言語名はその名前のまま */
12
+ readonly value: string;
13
+ }
14
+ export interface CodeLanguagePopoverController {
15
+ /** 基盤へ渡す拡張。セッション生成より前に取得する */
16
+ readonly extension: EditorExtension;
17
+ /** ポップアップを出すブロック。出さないときは `null` */
18
+ readonly block: SelectedCodeBlock | null;
19
+ /** 「なし」→(一覧に無い今の言語名)→ 一覧の言語 */
20
+ readonly options: readonly CodeLanguageOption[];
21
+ /** Select に示す今の言語。別名は正式な名前に直し、一覧に無い名前はそのまま */
22
+ readonly value: string;
23
+ /** ポップアップを出すブロックの DOM の要素。出さないときは `null` */
24
+ blockElement(): HTMLElement | null;
25
+ /** フォーカスがポップアップの中にあるか。部品が `focusin` / `focusout` で知らせる */
26
+ setPopoverFocused(focused: boolean): void;
27
+ /** Select で選ばれた。今と同じなら文書を変えない */
28
+ choose(value: string): void;
29
+ }
30
+ /**
31
+ * コードブロックの言語を選ぶポップアップの状態を、エディタ 1 インスタンスに閉じて持つ。
32
+ *
33
+ * **出すのは、編集エリアかポップアップのどちらかにフォーカスがあるときだけである。**
34
+ * Select は一覧を開くとフォーカスを移すので、ポップアップの中にフォーカスがあるあいだも
35
+ * 出し続ける。コンテキストメニューやショートカット一覧はフォーカスを取るので、これで消える。
36
+ *
37
+ * 選んだ後のフォーカスは Select に残す。書き手は Select を操作したのであり、続けて書く
38
+ * ならコードブロックを押せば戻れる。
39
+ *
40
+ * **エディタ 1 つにつき 1 つ生成する。** セッションは都度たどるだけで抱え込まない。
41
+ */
42
+ export declare function createCodeLanguagePopoverController(options: CodeLanguagePopoverControllerOptions): CodeLanguagePopoverController;