-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathInlineMath.ts
More file actions
288 lines (243 loc) · 6.69 KB
/
InlineMath.ts
File metadata and controls
288 lines (243 loc) · 6.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import { InputRule, mergeAttributes, Node } from '@tiptap/core'
import type { Node as PMNode } from '@tiptap/pm/model'
import katex, { type KatexOptions } from 'katex'
/**
* Configuration options for the InlineMath extension.
*/
export type InlineMathOptions = {
/**
* KaTeX specific options
* @see https://katex.org/docs/options.html
* @example
* ```ts
* katexOptions: {
* displayMode: false,
* throwOnError: false,
* macros: {
* '\\RR': '\\mathbb{R}',
* '\\ZZ': '\\mathbb{Z}'
* }
* }
* ```
*/
katexOptions?: KatexOptions
/**
* Optional click handler for inline math nodes.
* Called when a user clicks on an inline math expression in the editor.
*
* @param node - The ProseMirror node representing the inline math element
* @param pos - The position of the node within the document
* @example
* ```ts
* onClick: (node, pos) => {
* console.log('Inline math clicked:', node.attrs.latex, 'at position:', pos)
* }
* ```
*/
onClick?: (node: PMNode, pos: number) => void
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
inlineMath: {
/**
* Insert a inline math node with LaTeX string.
* @param options - Options for inserting inline math.
* @returns ReturnType
*/
insertInlineMath: (options: { latex: string; pos?: number }) => ReturnType
/**
* Delete an inline math node.
* @returns ReturnType
*/
deleteInlineMath: (options?: { pos?: number }) => ReturnType
/**
* Update inline math node with optional LaTeX string.
* @param options - Options for updating inline math.
* @returns ReturnType
*/
updateInlineMath: (options?: { latex?: string; pos?: number }) => ReturnType
}
}
}
/**
* InlineMath is a Tiptap extension for rendering inline mathematical expressions using KaTeX.
* It allows users to insert LaTeX formatted math expressions inline within text.
* It supports rendering, input rules for LaTeX syntax, and click handling for interaction.
*
* @example
* ```javascript
* import { InlineMath } from '@tiptap/extension-mathematics'
* import { Editor } from '@tiptap/core'
*
* const editor = new Editor({
* extensions: [
* InlineMath.configure({
* onClick: (node, pos) => {
* console.log('Inline math clicked:', node.attrs.latex, 'at position:', pos)
* },
* }),
* ],
* })
*/
export const InlineMath = Node.create<InlineMathOptions>({
name: 'inlineMath',
group: 'inline',
inline: true,
atom: true,
addOptions() {
return {
onClick: undefined,
katexOptions: undefined,
}
},
addAttributes() {
return {
latex: {
default: '',
parseHTML: element => element.getAttribute('data-latex'),
renderHTML: attributes => {
return {
'data-latex': attributes.latex,
}
},
},
}
},
addCommands() {
return {
insertInlineMath:
options =>
({ editor, tr }) => {
const latex = options.latex
const from = options?.pos ?? editor.state.selection.from
if (!latex) {
return false
}
tr.replaceWith(from, from, this.type.create({ latex }))
return true
},
deleteInlineMath:
options =>
({ editor, tr }) => {
const pos = options?.pos ?? editor.state.selection.$from.pos
const node = editor.state.doc.nodeAt(pos)
if (!node || node.type.name !== this.name) {
return false
}
tr.delete(pos, pos + node.nodeSize)
return true
},
updateInlineMath:
options =>
({ editor, tr }) => {
const latex = options?.latex
let pos = options?.pos
if (pos === undefined) {
pos = editor.state.selection.$from.pos
}
const node = editor.state.doc.nodeAt(pos)
if (!node || node.type.name !== this.name) {
return false
}
tr.setNodeMarkup(pos, this.type, { ...node.attrs, latex })
return true
},
}
},
parseHTML() {
return [
{
tag: 'span[data-type="inline-math"]',
},
]
},
renderHTML({ HTMLAttributes }) {
return ['span', mergeAttributes(HTMLAttributes, { 'data-type': 'inline-math' })]
},
parseMarkdown: (token: any) => {
return {
type: 'inlineMath',
attrs: {
latex: token.latex,
},
}
},
renderMarkdown: node => {
const latex = node.attrs?.latex || ''
return `$${latex}$`
},
markdownTokenizer: {
name: 'inlineMath',
level: 'inline',
start: (src: string) => src.indexOf('$'),
tokenize: (src: string) => {
// Match $latex$ syntax for inline math (but not $$)
const match = src.match(/^\$([^$]+)\$(?!\$)/)
if (!match) {
return undefined
}
const [fullMatch, latex] = match
return {
type: 'inlineMath',
raw: fullMatch,
latex: latex.trim(),
}
},
},
addInputRules() {
return [
new InputRule({
find: /(?<!$)(\$\$([^$\n]+?)\$\$)(?!\$)/,
handler: ({ state, range, match }) => {
const latex = match[3]
const { tr } = state
const start = range.from
const end = range.to
tr.replaceWith(start, end, this.type.create({ latex }))
},
}),
]
},
addNodeView() {
const { katexOptions } = this.options
return ({ node, getPos }) => {
const wrapper = document.createElement('span')
wrapper.className = 'tiptap-mathematics-render'
if (this.editor.isEditable) {
wrapper.classList.add('tiptap-mathematics-render--editable')
}
wrapper.dataset.type = 'inline-math'
wrapper.setAttribute('data-latex', node.attrs.latex)
function renderMath() {
try {
katex.render(node.attrs.latex, wrapper, katexOptions)
wrapper.classList.remove('inline-math-error')
} catch {
wrapper.textContent = node.attrs.latex
wrapper.classList.add('inline-math-error')
}
}
const handleClick = (event: MouseEvent) => {
event.preventDefault()
event.stopPropagation()
const pos = getPos()
if (pos == null) {
return
}
if (this.options.onClick) {
this.options.onClick(node, pos)
}
}
if (this.options.onClick) {
wrapper.addEventListener('click', handleClick)
}
renderMath()
return {
dom: wrapper,
destroy() {
wrapper.removeEventListener('click', handleClick)
},
}
}
},
})