@tiptap/extension-code-block 2.0.0-beta.9 → 2.0.0-rc.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.
@@ -0,0 +1,215 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tiptap/core'), require('@tiptap/pm/state')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@tiptap/core', '@tiptap/pm/state'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@tiptap/extension-code-block"] = {}, global.core, global.state));
5
+ })(this, (function (exports, core, state) { 'use strict';
6
+
7
+ const backtickInputRegex = /^```([a-z]+)?[\s\n]$/;
8
+ const tildeInputRegex = /^~~~([a-z]+)?[\s\n]$/;
9
+ const CodeBlock = core.Node.create({
10
+ name: 'codeBlock',
11
+ addOptions() {
12
+ return {
13
+ languageClassPrefix: 'language-',
14
+ exitOnTripleEnter: true,
15
+ exitOnArrowDown: true,
16
+ HTMLAttributes: {},
17
+ };
18
+ },
19
+ content: 'text*',
20
+ marks: '',
21
+ group: 'block',
22
+ code: true,
23
+ defining: true,
24
+ addAttributes() {
25
+ return {
26
+ language: {
27
+ default: null,
28
+ parseHTML: element => {
29
+ var _a;
30
+ const { languageClassPrefix } = this.options;
31
+ const classNames = [...(((_a = element.firstElementChild) === null || _a === void 0 ? void 0 : _a.classList) || [])];
32
+ const languages = classNames
33
+ .filter(className => className.startsWith(languageClassPrefix))
34
+ .map(className => className.replace(languageClassPrefix, ''));
35
+ const language = languages[0];
36
+ if (!language) {
37
+ return null;
38
+ }
39
+ return language;
40
+ },
41
+ rendered: false,
42
+ },
43
+ };
44
+ },
45
+ parseHTML() {
46
+ return [
47
+ {
48
+ tag: 'pre',
49
+ preserveWhitespace: 'full',
50
+ },
51
+ ];
52
+ },
53
+ renderHTML({ node, HTMLAttributes }) {
54
+ return [
55
+ 'pre',
56
+ core.mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
57
+ [
58
+ 'code',
59
+ {
60
+ class: node.attrs.language
61
+ ? this.options.languageClassPrefix + node.attrs.language
62
+ : null,
63
+ },
64
+ 0,
65
+ ],
66
+ ];
67
+ },
68
+ addCommands() {
69
+ return {
70
+ setCodeBlock: attributes => ({ commands }) => {
71
+ return commands.setNode(this.name, attributes);
72
+ },
73
+ toggleCodeBlock: attributes => ({ commands }) => {
74
+ return commands.toggleNode(this.name, 'paragraph', attributes);
75
+ },
76
+ };
77
+ },
78
+ addKeyboardShortcuts() {
79
+ return {
80
+ 'Mod-Alt-c': () => this.editor.commands.toggleCodeBlock(),
81
+ // remove code block when at start of document or code block is empty
82
+ Backspace: () => {
83
+ const { empty, $anchor } = this.editor.state.selection;
84
+ const isAtStart = $anchor.pos === 1;
85
+ if (!empty || $anchor.parent.type.name !== this.name) {
86
+ return false;
87
+ }
88
+ if (isAtStart || !$anchor.parent.textContent.length) {
89
+ return this.editor.commands.clearNodes();
90
+ }
91
+ return false;
92
+ },
93
+ // exit node on triple enter
94
+ Enter: ({ editor }) => {
95
+ if (!this.options.exitOnTripleEnter) {
96
+ return false;
97
+ }
98
+ const { state } = editor;
99
+ const { selection } = state;
100
+ const { $from, empty } = selection;
101
+ if (!empty || $from.parent.type !== this.type) {
102
+ return false;
103
+ }
104
+ const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;
105
+ const endsWithDoubleNewline = $from.parent.textContent.endsWith('\n\n');
106
+ if (!isAtEnd || !endsWithDoubleNewline) {
107
+ return false;
108
+ }
109
+ return editor
110
+ .chain()
111
+ .command(({ tr }) => {
112
+ tr.delete($from.pos - 2, $from.pos);
113
+ return true;
114
+ })
115
+ .exitCode()
116
+ .run();
117
+ },
118
+ // exit node on arrow down
119
+ ArrowDown: ({ editor }) => {
120
+ if (!this.options.exitOnArrowDown) {
121
+ return false;
122
+ }
123
+ const { state } = editor;
124
+ const { selection, doc } = state;
125
+ const { $from, empty } = selection;
126
+ if (!empty || $from.parent.type !== this.type) {
127
+ return false;
128
+ }
129
+ const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;
130
+ if (!isAtEnd) {
131
+ return false;
132
+ }
133
+ const after = $from.after();
134
+ if (after === undefined) {
135
+ return false;
136
+ }
137
+ const nodeAfter = doc.nodeAt(after);
138
+ if (nodeAfter) {
139
+ return false;
140
+ }
141
+ return editor.commands.exitCode();
142
+ },
143
+ };
144
+ },
145
+ addInputRules() {
146
+ return [
147
+ core.textblockTypeInputRule({
148
+ find: backtickInputRegex,
149
+ type: this.type,
150
+ getAttributes: match => ({
151
+ language: match[1],
152
+ }),
153
+ }),
154
+ core.textblockTypeInputRule({
155
+ find: tildeInputRegex,
156
+ type: this.type,
157
+ getAttributes: match => ({
158
+ language: match[1],
159
+ }),
160
+ }),
161
+ ];
162
+ },
163
+ addProseMirrorPlugins() {
164
+ return [
165
+ // this plugin creates a code block for pasted content from VS Code
166
+ // we can also detect the copied code language
167
+ new state.Plugin({
168
+ key: new state.PluginKey('codeBlockVSCodeHandler'),
169
+ props: {
170
+ handlePaste: (view, event) => {
171
+ if (!event.clipboardData) {
172
+ return false;
173
+ }
174
+ // don’t create a new code block within code blocks
175
+ if (this.editor.isActive(this.type.name)) {
176
+ return false;
177
+ }
178
+ const text = event.clipboardData.getData('text/plain');
179
+ const vscode = event.clipboardData.getData('vscode-editor-data');
180
+ const vscodeData = vscode ? JSON.parse(vscode) : undefined;
181
+ const language = vscodeData === null || vscodeData === void 0 ? void 0 : vscodeData.mode;
182
+ if (!text || !language) {
183
+ return false;
184
+ }
185
+ const { tr } = view.state;
186
+ // create an empty code block
187
+ tr.replaceSelectionWith(this.type.create({ language }));
188
+ // put cursor inside the newly created code block
189
+ tr.setSelection(state.TextSelection.near(tr.doc.resolve(Math.max(0, tr.selection.from - 2))));
190
+ // add text to code block
191
+ // strip carriage return chars from text pasted as code
192
+ // see: https://github.com/ProseMirror/prosemirror-view/commit/a50a6bcceb4ce52ac8fcc6162488d8875613aacd
193
+ tr.insertText(text.replace(/\r\n?/g, '\n'));
194
+ // store meta information
195
+ // this is useful for other plugins that depends on the paste event
196
+ // like the paste rule plugin
197
+ tr.setMeta('paste', true);
198
+ view.dispatch(tr);
199
+ return true;
200
+ },
201
+ },
202
+ }),
203
+ ];
204
+ },
205
+ });
206
+
207
+ exports.CodeBlock = CodeBlock;
208
+ exports.backtickInputRegex = backtickInputRegex;
209
+ exports["default"] = CodeBlock;
210
+ exports.tildeInputRegex = tildeInputRegex;
211
+
212
+ Object.defineProperty(exports, '__esModule', { value: true });
213
+
214
+ }));
215
+ //# sourceMappingURL=index.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.umd.js","sources":["../src/code-block.ts"],"sourcesContent":["import { mergeAttributes, Node, textblockTypeInputRule } from '@tiptap/core'\nimport { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'\n\nexport interface CodeBlockOptions {\n /**\n * Adds a prefix to language classes that are applied to code tags.\n * Defaults to `'language-'`.\n */\n languageClassPrefix: string\n /**\n * Define whether the node should be exited on triple enter.\n * Defaults to `true`.\n */\n exitOnTripleEnter: boolean\n /**\n * Define whether the node should be exited on arrow down if there is no node after it.\n * Defaults to `true`.\n */\n exitOnArrowDown: boolean\n /**\n * Custom HTML attributes that should be added to the rendered HTML tag.\n */\n HTMLAttributes: Record<string, any>\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n codeBlock: {\n /**\n * Set a code block\n */\n setCodeBlock: (attributes?: { language: string }) => ReturnType\n /**\n * Toggle a code block\n */\n toggleCodeBlock: (attributes?: { language: string }) => ReturnType\n }\n }\n}\n\nexport const backtickInputRegex = /^```([a-z]+)?[\\s\\n]$/\nexport const tildeInputRegex = /^~~~([a-z]+)?[\\s\\n]$/\n\nexport const CodeBlock = Node.create<CodeBlockOptions>({\n name: 'codeBlock',\n\n addOptions() {\n return {\n languageClassPrefix: 'language-',\n exitOnTripleEnter: true,\n exitOnArrowDown: true,\n HTMLAttributes: {},\n }\n },\n\n content: 'text*',\n\n marks: '',\n\n group: 'block',\n\n code: true,\n\n defining: true,\n\n addAttributes() {\n return {\n language: {\n default: null,\n parseHTML: element => {\n const { languageClassPrefix } = this.options\n const classNames = [...(element.firstElementChild?.classList || [])]\n const languages = classNames\n .filter(className => className.startsWith(languageClassPrefix))\n .map(className => className.replace(languageClassPrefix, ''))\n const language = languages[0]\n\n if (!language) {\n return null\n }\n\n return language\n },\n rendered: false,\n },\n }\n },\n\n parseHTML() {\n return [\n {\n tag: 'pre',\n preserveWhitespace: 'full',\n },\n ]\n },\n\n renderHTML({ node, HTMLAttributes }) {\n return [\n 'pre',\n mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),\n [\n 'code',\n {\n class: node.attrs.language\n ? this.options.languageClassPrefix + node.attrs.language\n : null,\n },\n 0,\n ],\n ]\n },\n\n addCommands() {\n return {\n setCodeBlock:\n attributes => ({ commands }) => {\n return commands.setNode(this.name, attributes)\n },\n toggleCodeBlock:\n attributes => ({ commands }) => {\n return commands.toggleNode(this.name, 'paragraph', attributes)\n },\n }\n },\n\n addKeyboardShortcuts() {\n return {\n 'Mod-Alt-c': () => this.editor.commands.toggleCodeBlock(),\n\n // remove code block when at start of document or code block is empty\n Backspace: () => {\n const { empty, $anchor } = this.editor.state.selection\n const isAtStart = $anchor.pos === 1\n\n if (!empty || $anchor.parent.type.name !== this.name) {\n return false\n }\n\n if (isAtStart || !$anchor.parent.textContent.length) {\n return this.editor.commands.clearNodes()\n }\n\n return false\n },\n\n // exit node on triple enter\n Enter: ({ editor }) => {\n if (!this.options.exitOnTripleEnter) {\n return false\n }\n\n const { state } = editor\n const { selection } = state\n const { $from, empty } = selection\n\n if (!empty || $from.parent.type !== this.type) {\n return false\n }\n\n const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2\n const endsWithDoubleNewline = $from.parent.textContent.endsWith('\\n\\n')\n\n if (!isAtEnd || !endsWithDoubleNewline) {\n return false\n }\n\n return editor\n .chain()\n .command(({ tr }) => {\n tr.delete($from.pos - 2, $from.pos)\n\n return true\n })\n .exitCode()\n .run()\n },\n\n // exit node on arrow down\n ArrowDown: ({ editor }) => {\n if (!this.options.exitOnArrowDown) {\n return false\n }\n\n const { state } = editor\n const { selection, doc } = state\n const { $from, empty } = selection\n\n if (!empty || $from.parent.type !== this.type) {\n return false\n }\n\n const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2\n\n if (!isAtEnd) {\n return false\n }\n\n const after = $from.after()\n\n if (after === undefined) {\n return false\n }\n\n const nodeAfter = doc.nodeAt(after)\n\n if (nodeAfter) {\n return false\n }\n\n return editor.commands.exitCode()\n },\n }\n },\n\n addInputRules() {\n return [\n textblockTypeInputRule({\n find: backtickInputRegex,\n type: this.type,\n getAttributes: match => ({\n language: match[1],\n }),\n }),\n textblockTypeInputRule({\n find: tildeInputRegex,\n type: this.type,\n getAttributes: match => ({\n language: match[1],\n }),\n }),\n ]\n },\n\n addProseMirrorPlugins() {\n return [\n // this plugin creates a code block for pasted content from VS Code\n // we can also detect the copied code language\n new Plugin({\n key: new PluginKey('codeBlockVSCodeHandler'),\n props: {\n handlePaste: (view, event) => {\n if (!event.clipboardData) {\n return false\n }\n\n // don’t create a new code block within code blocks\n if (this.editor.isActive(this.type.name)) {\n return false\n }\n\n const text = event.clipboardData.getData('text/plain')\n const vscode = event.clipboardData.getData('vscode-editor-data')\n const vscodeData = vscode ? JSON.parse(vscode) : undefined\n const language = vscodeData?.mode\n\n if (!text || !language) {\n return false\n }\n\n const { tr } = view.state\n\n // create an empty code block\n tr.replaceSelectionWith(this.type.create({ language }))\n\n // put cursor inside the newly created code block\n tr.setSelection(TextSelection.near(tr.doc.resolve(Math.max(0, tr.selection.from - 2))))\n\n // add text to code block\n // strip carriage return chars from text pasted as code\n // see: https://github.com/ProseMirror/prosemirror-view/commit/a50a6bcceb4ce52ac8fcc6162488d8875613aacd\n tr.insertText(text.replace(/\\r\\n?/g, '\\n'))\n\n // store meta information\n // this is useful for other plugins that depends on the paste event\n // like the paste rule plugin\n tr.setMeta('paste', true)\n\n view.dispatch(tr)\n\n return true\n },\n },\n }),\n ]\n },\n})\n"],"names":["Node","mergeAttributes","textblockTypeInputRule","Plugin","PluginKey","TextSelection"],"mappings":";;;;;;AAwCO,QAAM,kBAAkB,GAAG,uBAAsB;AACjD,QAAM,eAAe,GAAG,uBAAsB;AAExC,QAAA,SAAS,GAAGA,SAAI,CAAC,MAAM,CAAmB;EACrD,IAAA,IAAI,EAAE,WAAW;MAEjB,UAAU,GAAA;UACR,OAAO;EACL,YAAA,mBAAmB,EAAE,WAAW;EAChC,YAAA,iBAAiB,EAAE,IAAI;EACvB,YAAA,eAAe,EAAE,IAAI;EACrB,YAAA,cAAc,EAAE,EAAE;WACnB,CAAA;OACF;EAED,IAAA,OAAO,EAAE,OAAO;EAEhB,IAAA,KAAK,EAAE,EAAE;EAET,IAAA,KAAK,EAAE,OAAO;EAEd,IAAA,IAAI,EAAE,IAAI;EAEV,IAAA,QAAQ,EAAE,IAAI;MAEd,aAAa,GAAA;UACX,OAAO;EACL,YAAA,QAAQ,EAAE;EACR,gBAAA,OAAO,EAAE,IAAI;kBACb,SAAS,EAAE,OAAO,IAAG;;EACnB,oBAAA,MAAM,EAAE,mBAAmB,EAAE,GAAG,IAAI,CAAC,OAAO,CAAA;EAC5C,oBAAA,MAAM,UAAU,GAAG,CAAC,IAAI,CAAA,CAAA,EAAA,GAAA,OAAO,CAAC,iBAAiB,0CAAE,SAAS,KAAI,EAAE,CAAC,CAAC,CAAA;sBACpE,MAAM,SAAS,GAAG,UAAU;2BACzB,MAAM,CAAC,SAAS,IAAI,SAAS,CAAC,UAAU,CAAC,mBAAmB,CAAC,CAAC;EAC9D,yBAAA,GAAG,CAAC,SAAS,IAAI,SAAS,CAAC,OAAO,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC,CAAA;EAC/D,oBAAA,MAAM,QAAQ,GAAG,SAAS,CAAC,CAAC,CAAC,CAAA;sBAE7B,IAAI,CAAC,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,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,SAAS,CAAA;0BAC1D,MAAM,QAAQ,GAAG,UAAU,KAAA,IAAA,IAAV,UAAU,KAAV,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,UAAU,CAAE,IAAI,CAAA;EAEjC,wBAAA,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE;EACtB,4BAAA,OAAO,KAAK,CAAA;EACb,yBAAA;EAED,wBAAA,MAAM,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC,KAAK,CAAA;;EAGzB,wBAAA,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAA;;EAGvD,wBAAA,EAAE,CAAC,YAAY,CAACC,mBAAa,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;;;;EAKvF,wBAAA,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAA;;;;EAK3C,wBAAA,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;EAEzB,wBAAA,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAA;EAEjB,wBAAA,OAAO,IAAI,CAAA;uBACZ;EACF,iBAAA;eACF,CAAC;WACH,CAAA;OACF;EACF,CAAA;;;;;;;;;;;;;"}
@@ -1,26 +1,43 @@
1
- import { Command, Node } from '@tiptap/core';
1
+ import { Node } from '@tiptap/core';
2
2
  export interface CodeBlockOptions {
3
+ /**
4
+ * Adds a prefix to language classes that are applied to code tags.
5
+ * Defaults to `'language-'`.
6
+ */
3
7
  languageClassPrefix: string;
8
+ /**
9
+ * Define whether the node should be exited on triple enter.
10
+ * Defaults to `true`.
11
+ */
12
+ exitOnTripleEnter: boolean;
13
+ /**
14
+ * Define whether the node should be exited on arrow down if there is no node after it.
15
+ * Defaults to `true`.
16
+ */
17
+ exitOnArrowDown: boolean;
18
+ /**
19
+ * Custom HTML attributes that should be added to the rendered HTML tag.
20
+ */
4
21
  HTMLAttributes: Record<string, any>;
5
22
  }
6
23
  declare module '@tiptap/core' {
7
- interface Commands {
24
+ interface Commands<ReturnType> {
8
25
  codeBlock: {
9
26
  /**
10
27
  * Set a code block
11
28
  */
12
29
  setCodeBlock: (attributes?: {
13
30
  language: string;
14
- }) => Command;
31
+ }) => ReturnType;
15
32
  /**
16
33
  * Toggle a code block
17
34
  */
18
35
  toggleCodeBlock: (attributes?: {
19
36
  language: string;
20
- }) => Command;
37
+ }) => ReturnType;
21
38
  };
22
39
  }
23
40
  }
24
41
  export declare const backtickInputRegex: RegExp;
25
42
  export declare const tildeInputRegex: RegExp;
26
- export declare const CodeBlock: Node<CodeBlockOptions>;
43
+ export declare const CodeBlock: Node<CodeBlockOptions, any>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tiptap/extension-code-block",
3
3
  "description": "code block extension for tiptap",
4
- "version": "2.0.0-beta.9",
4
+ "version": "2.0.0-rc.1",
5
5
  "homepage": "https://tiptap.dev",
6
6
  "keywords": [
7
7
  "tiptap",
@@ -12,19 +12,37 @@
12
12
  "type": "github",
13
13
  "url": "https://github.com/sponsors/ueberdosis"
14
14
  },
15
- "main": "dist/tiptap-extension-code-block.cjs.js",
16
- "umd": "dist/tiptap-extension-code-block.umd.js",
17
- "module": "dist/tiptap-extension-code-block.esm.js",
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/packages/extension-code-block/src/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "require": "./dist/index.cjs"
21
+ }
22
+ },
23
+ "main": "dist/index.cjs",
24
+ "module": "dist/index.js",
25
+ "umd": "dist/index.umd.js",
18
26
  "types": "dist/packages/extension-code-block/src/index.d.ts",
19
27
  "files": [
20
28
  "src",
21
29
  "dist"
22
30
  ],
23
31
  "peerDependencies": {
24
- "@tiptap/core": "^2.0.0-beta.1"
32
+ "@tiptap/core": "2.0.0-rc.1",
33
+ "@tiptap/pm": "2.0.0-rc.1"
34
+ },
35
+ "devDependencies": {
36
+ "@tiptap/core": "2.0.0-rc.1",
37
+ "@tiptap/pm": "2.0.0-rc.1"
25
38
  },
26
- "dependencies": {
27
- "prosemirror-inputrules": "^1.1.3"
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/ueberdosis/tiptap",
42
+ "directory": "packages/extension-code-block"
28
43
  },
29
- "gitHead": "c64520b74dab6b127c78960c1bd0af237b1f68fb"
30
- }
44
+ "scripts": {
45
+ "clean": "rm -rf dist",
46
+ "build": "npm run clean && rollup -c"
47
+ }
48
+ }
package/src/code-block.ts CHANGED
@@ -1,35 +1,56 @@
1
- import { Command, Node } from '@tiptap/core'
2
- import { textblockTypeInputRule } from 'prosemirror-inputrules'
1
+ import { mergeAttributes, Node, textblockTypeInputRule } from '@tiptap/core'
2
+ import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'
3
3
 
4
4
  export interface CodeBlockOptions {
5
- languageClassPrefix: string,
6
- HTMLAttributes: Record<string, any>,
5
+ /**
6
+ * Adds a prefix to language classes that are applied to code tags.
7
+ * Defaults to `'language-'`.
8
+ */
9
+ languageClassPrefix: string
10
+ /**
11
+ * Define whether the node should be exited on triple enter.
12
+ * Defaults to `true`.
13
+ */
14
+ exitOnTripleEnter: boolean
15
+ /**
16
+ * Define whether the node should be exited on arrow down if there is no node after it.
17
+ * Defaults to `true`.
18
+ */
19
+ exitOnArrowDown: boolean
20
+ /**
21
+ * Custom HTML attributes that should be added to the rendered HTML tag.
22
+ */
23
+ HTMLAttributes: Record<string, any>
7
24
  }
8
25
 
9
26
  declare module '@tiptap/core' {
10
- interface Commands {
27
+ interface Commands<ReturnType> {
11
28
  codeBlock: {
12
29
  /**
13
30
  * Set a code block
14
31
  */
15
- setCodeBlock: (attributes?: { language: string }) => Command,
32
+ setCodeBlock: (attributes?: { language: string }) => ReturnType
16
33
  /**
17
34
  * Toggle a code block
18
35
  */
19
- toggleCodeBlock: (attributes?: { language: string }) => Command,
36
+ toggleCodeBlock: (attributes?: { language: string }) => ReturnType
20
37
  }
21
38
  }
22
39
  }
23
40
 
24
- export const backtickInputRegex = /^```(?<language>[a-z]*)? $/
25
- export const tildeInputRegex = /^~~~(?<language>[a-z]*)? $/
41
+ export const backtickInputRegex = /^```([a-z]+)?[\s\n]$/
42
+ export const tildeInputRegex = /^~~~([a-z]+)?[\s\n]$/
26
43
 
27
44
  export const CodeBlock = Node.create<CodeBlockOptions>({
28
45
  name: 'codeBlock',
29
46
 
30
- defaultOptions: {
31
- languageClassPrefix: 'language-',
32
- HTMLAttributes: {},
47
+ addOptions() {
48
+ return {
49
+ languageClassPrefix: 'language-',
50
+ exitOnTripleEnter: true,
51
+ exitOnArrowDown: true,
52
+ HTMLAttributes: {},
53
+ }
33
54
  },
34
55
 
35
56
  content: 'text*',
@@ -47,27 +68,20 @@ export const CodeBlock = Node.create<CodeBlockOptions>({
47
68
  language: {
48
69
  default: null,
49
70
  parseHTML: element => {
50
- const classAttribute = element.firstElementChild?.getAttribute('class')
71
+ const { languageClassPrefix } = this.options
72
+ const classNames = [...(element.firstElementChild?.classList || [])]
73
+ const languages = classNames
74
+ .filter(className => className.startsWith(languageClassPrefix))
75
+ .map(className => className.replace(languageClassPrefix, ''))
76
+ const language = languages[0]
51
77
 
52
- if (!classAttribute) {
78
+ if (!language) {
53
79
  return null
54
80
  }
55
81
 
56
- const regexLanguageClassPrefix = new RegExp(`^(${this.options.languageClassPrefix})`)
57
-
58
- return {
59
- language: classAttribute.replace(regexLanguageClassPrefix, ''),
60
- }
61
- },
62
- renderHTML: attributes => {
63
- if (!attributes.language) {
64
- return null
65
- }
66
-
67
- return {
68
- class: this.options.languageClassPrefix + attributes.language,
69
- }
82
+ return language
70
83
  },
84
+ rendered: false,
71
85
  },
72
86
  }
73
87
  },
@@ -81,18 +95,32 @@ export const CodeBlock = Node.create<CodeBlockOptions>({
81
95
  ]
82
96
  },
83
97
 
84
- renderHTML({ HTMLAttributes }) {
85
- return ['pre', this.options.HTMLAttributes, ['code', HTMLAttributes, 0]]
98
+ renderHTML({ node, HTMLAttributes }) {
99
+ return [
100
+ 'pre',
101
+ mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
102
+ [
103
+ 'code',
104
+ {
105
+ class: node.attrs.language
106
+ ? this.options.languageClassPrefix + node.attrs.language
107
+ : null,
108
+ },
109
+ 0,
110
+ ],
111
+ ]
86
112
  },
87
113
 
88
114
  addCommands() {
89
115
  return {
90
- setCodeBlock: attributes => ({ commands }) => {
91
- return commands.setNode('codeBlock', attributes)
92
- },
93
- toggleCodeBlock: attributes => ({ commands }) => {
94
- return commands.toggleNode('codeBlock', 'paragraph', attributes)
95
- },
116
+ setCodeBlock:
117
+ attributes => ({ commands }) => {
118
+ return commands.setNode(this.name, attributes)
119
+ },
120
+ toggleCodeBlock:
121
+ attributes => ({ commands }) => {
122
+ return commands.toggleNode(this.name, 'paragraph', attributes)
123
+ },
96
124
  }
97
125
  },
98
126
 
@@ -115,13 +143,145 @@ export const CodeBlock = Node.create<CodeBlockOptions>({
115
143
 
116
144
  return false
117
145
  },
146
+
147
+ // exit node on triple enter
148
+ Enter: ({ editor }) => {
149
+ if (!this.options.exitOnTripleEnter) {
150
+ return false
151
+ }
152
+
153
+ const { state } = editor
154
+ const { selection } = state
155
+ const { $from, empty } = selection
156
+
157
+ if (!empty || $from.parent.type !== this.type) {
158
+ return false
159
+ }
160
+
161
+ const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2
162
+ const endsWithDoubleNewline = $from.parent.textContent.endsWith('\n\n')
163
+
164
+ if (!isAtEnd || !endsWithDoubleNewline) {
165
+ return false
166
+ }
167
+
168
+ return editor
169
+ .chain()
170
+ .command(({ tr }) => {
171
+ tr.delete($from.pos - 2, $from.pos)
172
+
173
+ return true
174
+ })
175
+ .exitCode()
176
+ .run()
177
+ },
178
+
179
+ // exit node on arrow down
180
+ ArrowDown: ({ editor }) => {
181
+ if (!this.options.exitOnArrowDown) {
182
+ return false
183
+ }
184
+
185
+ const { state } = editor
186
+ const { selection, doc } = state
187
+ const { $from, empty } = selection
188
+
189
+ if (!empty || $from.parent.type !== this.type) {
190
+ return false
191
+ }
192
+
193
+ const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2
194
+
195
+ if (!isAtEnd) {
196
+ return false
197
+ }
198
+
199
+ const after = $from.after()
200
+
201
+ if (after === undefined) {
202
+ return false
203
+ }
204
+
205
+ const nodeAfter = doc.nodeAt(after)
206
+
207
+ if (nodeAfter) {
208
+ return false
209
+ }
210
+
211
+ return editor.commands.exitCode()
212
+ },
118
213
  }
119
214
  },
120
215
 
121
216
  addInputRules() {
122
217
  return [
123
- textblockTypeInputRule(backtickInputRegex, this.type, ({ groups }: any) => groups),
124
- textblockTypeInputRule(tildeInputRegex, this.type, ({ groups }: any) => groups),
218
+ textblockTypeInputRule({
219
+ find: backtickInputRegex,
220
+ type: this.type,
221
+ getAttributes: match => ({
222
+ language: match[1],
223
+ }),
224
+ }),
225
+ textblockTypeInputRule({
226
+ find: tildeInputRegex,
227
+ type: this.type,
228
+ getAttributes: match => ({
229
+ language: match[1],
230
+ }),
231
+ }),
232
+ ]
233
+ },
234
+
235
+ addProseMirrorPlugins() {
236
+ return [
237
+ // this plugin creates a code block for pasted content from VS Code
238
+ // we can also detect the copied code language
239
+ new Plugin({
240
+ key: new PluginKey('codeBlockVSCodeHandler'),
241
+ props: {
242
+ handlePaste: (view, event) => {
243
+ if (!event.clipboardData) {
244
+ return false
245
+ }
246
+
247
+ // don’t create a new code block within code blocks
248
+ if (this.editor.isActive(this.type.name)) {
249
+ return false
250
+ }
251
+
252
+ const text = event.clipboardData.getData('text/plain')
253
+ const vscode = event.clipboardData.getData('vscode-editor-data')
254
+ const vscodeData = vscode ? JSON.parse(vscode) : undefined
255
+ const language = vscodeData?.mode
256
+
257
+ if (!text || !language) {
258
+ return false
259
+ }
260
+
261
+ const { tr } = view.state
262
+
263
+ // create an empty code block
264
+ tr.replaceSelectionWith(this.type.create({ language }))
265
+
266
+ // put cursor inside the newly created code block
267
+ tr.setSelection(TextSelection.near(tr.doc.resolve(Math.max(0, tr.selection.from - 2))))
268
+
269
+ // add text to code block
270
+ // strip carriage return chars from text pasted as code
271
+ // see: https://github.com/ProseMirror/prosemirror-view/commit/a50a6bcceb4ce52ac8fcc6162488d8875613aacd
272
+ tr.insertText(text.replace(/\r\n?/g, '\n'))
273
+
274
+ // store meta information
275
+ // this is useful for other plugins that depends on the paste event
276
+ // like the paste rule plugin
277
+ tr.setMeta('paste', true)
278
+
279
+ view.dispatch(tr)
280
+
281
+ return true
282
+ },
283
+ },
284
+ }),
125
285
  ]
126
286
  },
127
287
  })