paste-html.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. import { EditorView } from '@codemirror/view'
  2. import { EditorSelection, Prec } from '@codemirror/state'
  3. export const pasteHtml = Prec.highest(
  4. EditorView.domEventHandlers({
  5. paste(event, view) {
  6. const { clipboardData } = event
  7. if (!clipboardData?.types.includes('text/html')) {
  8. return false
  9. }
  10. const html = clipboardData.getData('text/html').trim()
  11. if (html.length === 0) {
  12. return false
  13. }
  14. // convert the HTML to LaTeX
  15. try {
  16. const latex = htmlToLaTeX(html)
  17. view.dispatch(
  18. view.state.changeByRange(range => {
  19. return {
  20. range: EditorSelection.cursor(range.from + latex.length),
  21. changes: { from: range.from, to: range.to, insert: latex },
  22. }
  23. })
  24. )
  25. return true
  26. } catch (error) {
  27. console.error(error)
  28. // fall back to the default paste handler
  29. return false
  30. }
  31. },
  32. })
  33. )
  34. const removeUnwantedElements = (
  35. documentElement: HTMLElement,
  36. selector: string
  37. ) => {
  38. for (const element of documentElement.querySelectorAll(selector)) {
  39. element.remove()
  40. }
  41. }
  42. const htmlToLaTeX = (html: string) => {
  43. const parser = new DOMParser()
  44. const { documentElement } = parser.parseFromString(html, 'text/html')
  45. // remove style elements
  46. removeUnwantedElements(documentElement, 'style')
  47. // pre-process table elements
  48. processTables(documentElement)
  49. // protect special characters in non-LaTeX text nodes
  50. protectSpecialCharacters(documentElement)
  51. processMatchedElements(documentElement)
  52. const text = documentElement.textContent
  53. if (!text) {
  54. return ''
  55. }
  56. // normalise multiple newlines
  57. return text.replaceAll(/\n{2,}/g, '\n\n')
  58. }
  59. const protectSpecialCharacters = (documentElement: HTMLElement) => {
  60. for (const element of documentElement.childNodes) {
  61. const text = element.textContent
  62. if (text) {
  63. // if there are no code blocks, use backslash as an indicator of LaTeX code that shouldn't be protected
  64. if (
  65. element instanceof HTMLElement &&
  66. !element.querySelector('code') &&
  67. text.includes('\\')
  68. ) {
  69. continue
  70. }
  71. const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT)
  72. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  73. const text = node.textContent
  74. if (text) {
  75. // leave text that's in a code block
  76. if (node.parentElement?.closest('code')) {
  77. continue
  78. }
  79. // replace non-backslash-prefixed characters
  80. node.textContent = text.replaceAll(
  81. /(^|[^\\])([#$%&~_^\\{}])/g,
  82. (_match, prefix: string, char: string) => `${prefix}\\${char}`
  83. )
  84. }
  85. }
  86. }
  87. }
  88. }
  89. const processMatchedElements = (documentElement: HTMLElement) => {
  90. for (const item of selectors) {
  91. for (const element of documentElement.querySelectorAll<any>(
  92. item.selector
  93. )) {
  94. if (!item.match || item.match(element)) {
  95. // start the markup
  96. if (item.start) {
  97. const start = document.createTextNode(item.start(element))
  98. if (item.inside) {
  99. element.prepend(start)
  100. } else {
  101. element.before(start)
  102. }
  103. }
  104. // end the markup
  105. if (item.end) {
  106. const end = document.createTextNode(item.end(element))
  107. if (item.inside) {
  108. element.append(end)
  109. } else {
  110. element.after(end)
  111. }
  112. }
  113. }
  114. }
  115. }
  116. }
  117. const matchingParents = (element: HTMLElement, selector: string) => {
  118. const matches = []
  119. for (
  120. let ancestor = element.parentElement?.closest(selector);
  121. ancestor;
  122. ancestor = ancestor.parentElement?.closest(selector)
  123. ) {
  124. matches.push(ancestor)
  125. }
  126. return matches
  127. }
  128. const processTables = (element: HTMLElement) => {
  129. for (const table of element.querySelectorAll('table')) {
  130. // create a wrapper element for the table and the caption
  131. const container = document.createElement('div')
  132. container.className = 'ol-table-wrap'
  133. table.after(container)
  134. // move the caption (if it exists) into the container before the table
  135. const caption = table.querySelector('caption')
  136. if (caption) {
  137. container.append(caption)
  138. }
  139. // move the table into the container
  140. container.append(table)
  141. }
  142. }
  143. const tabular = (element: HTMLTableElement) => {
  144. const options = []
  145. // NOTE: only analysing cells in the first row
  146. const row = element.querySelector('tr')
  147. if (row) {
  148. // TODO: look for horizontal borders and insert \hline (or \toprule, \midrule, \bottomrule etc)?
  149. const cells = [...row.childNodes].filter(
  150. element => element.nodeName === 'TD' || element.nodeName === 'TH'
  151. ) as Array<HTMLTableCellElement | HTMLTableHeaderCellElement>
  152. for (const cell of cells) {
  153. const { borderLeft, textAlign, borderRight } = cell.style
  154. if (borderLeft && borderLeft !== 'none') {
  155. // avoid duplicating when both left and right borders are defined
  156. if (options.length === 0 || options[options.length - 1] !== '|') {
  157. options.push('|')
  158. }
  159. }
  160. options.push(
  161. textAlign === 'left' ? 'l' : textAlign === 'right' ? 'r' : 'c'
  162. )
  163. if (borderRight && borderRight !== 'none') {
  164. options.push('|')
  165. }
  166. }
  167. }
  168. return options.join(' ')
  169. }
  170. const listDepth = (
  171. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  172. ): number => Math.max(0, matchingParents(element, 'ul,ol').length - 1)
  173. const listIndent = (
  174. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  175. ): string => '\t'.repeat(listDepth(element))
  176. type ElementSelector<T extends string, E extends HTMLElement = HTMLElement> = {
  177. selector: T
  178. match?: (element: E) => boolean
  179. start?: (element: E) => string
  180. end?: (element: E) => string
  181. inside?: boolean
  182. }
  183. const createSelector = <
  184. T extends string,
  185. E extends HTMLElement = T extends keyof HTMLElementTagNameMap
  186. ? HTMLElementTagNameMap[T]
  187. : HTMLElement
  188. >({
  189. selector,
  190. ...elementSelector
  191. }: ElementSelector<T, E>) => ({
  192. selector,
  193. ...elementSelector,
  194. })
  195. const headings = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']
  196. const isHeading = (element: HTMLElement | null) => {
  197. return element && headings.includes(element.nodeName)
  198. }
  199. const hasContent = (element: HTMLElement): boolean => {
  200. return Boolean(element.textContent && element.textContent.trim().length > 0)
  201. }
  202. export const selectors = [
  203. createSelector({
  204. selector: 'b',
  205. match: element =>
  206. element.style.fontWeight !== 'normal' &&
  207. !isHeading(element.parentElement) &&
  208. hasContent(element),
  209. start: () => '\\textbf{',
  210. end: () => '}',
  211. }),
  212. createSelector({
  213. selector: '*',
  214. match: element =>
  215. parseInt(element.style.fontWeight) > 400 && hasContent(element),
  216. start: () => '\\textbf{',
  217. end: () => '}',
  218. inside: true,
  219. }),
  220. createSelector({
  221. selector: 'i',
  222. match: element =>
  223. element.style.fontStyle !== 'normal' && hasContent(element),
  224. start: () => '\\textit{',
  225. end: () => '}',
  226. }),
  227. createSelector({
  228. selector: '*',
  229. match: element =>
  230. element.style.fontStyle === 'italic' && hasContent(element),
  231. start: () => '\\textit{',
  232. end: () => '}',
  233. }),
  234. createSelector({
  235. selector: 'sup',
  236. match: element => hasContent(element),
  237. start: () => '\\textsuperscript{',
  238. end: () => '}',
  239. }),
  240. createSelector({
  241. selector: 'span',
  242. match: element =>
  243. element.style.verticalAlign === 'super' && hasContent(element),
  244. start: () => '\\textsuperscript{',
  245. end: () => '}',
  246. }),
  247. createSelector({
  248. selector: 'sub',
  249. match: element => hasContent(element),
  250. start: () => '\\textsubscript{',
  251. end: () => '}',
  252. }),
  253. createSelector({
  254. selector: 'span',
  255. match: element =>
  256. element.style.verticalAlign === 'sub' && hasContent(element),
  257. start: () => '\\textsubscript{',
  258. end: () => '}',
  259. }),
  260. createSelector({
  261. selector: 'a',
  262. match: element => !!element.href && hasContent(element),
  263. start: (element: HTMLAnchorElement) => `\\href{${element.href}}{`,
  264. end: element => `}`,
  265. }),
  266. createSelector({
  267. selector: 'h1',
  268. match: element => !element.closest('table') && hasContent(element),
  269. start: () => `\n\n\\section{`,
  270. end: () => `}\n\n`,
  271. }),
  272. createSelector({
  273. selector: 'h2',
  274. match: element => !element.closest('table') && hasContent(element),
  275. start: () => `\n\n\\subsection{`,
  276. end: () => `}\n\n`,
  277. }),
  278. createSelector({
  279. selector: 'h3',
  280. match: element => !element.closest('table') && hasContent(element),
  281. start: () => `\n\n\\subsubsection{`,
  282. end: () => `}\n\n`,
  283. }),
  284. createSelector({
  285. selector: 'h4',
  286. match: element => !element.closest('table') && hasContent(element),
  287. start: () => `\n\n\\paragraph{`,
  288. end: () => `}\n\n`,
  289. }),
  290. createSelector({
  291. selector: 'h5',
  292. match: element => !element.closest('table') && hasContent(element),
  293. start: () => `\n\n\\subparagraph{`,
  294. end: () => `}\n\n`,
  295. }),
  296. // TODO: h6?
  297. createSelector({
  298. selector: 'br',
  299. match: element => element.parentElement?.nodeName !== 'TD', // TODO: why?
  300. start: () => `\n\n`,
  301. }),
  302. createSelector({
  303. selector: 'code',
  304. match: element =>
  305. element.parentElement?.nodeName !== 'PRE' && hasContent(element),
  306. start: () => `\\verb|`,
  307. end: () => `|`,
  308. }),
  309. createSelector({
  310. selector: 'pre > code',
  311. match: element => hasContent(element),
  312. start: () => `\n\n\\begin{verbatim}\n`,
  313. end: () => `\n\\end{verbatim}\n\n`,
  314. }),
  315. createSelector({
  316. selector: '.ol-table-wrap',
  317. start: element => `\n\n\\begin{table}\n\\centering\n`,
  318. end: () => `\n\\end{table}\n\n`,
  319. }),
  320. createSelector({
  321. selector: 'table',
  322. start: element => `\n\\begin{tabular}{${tabular(element)}}\n`,
  323. end: () => `\n\\end{tabular}\n`,
  324. }),
  325. createSelector({
  326. selector: 'thead',
  327. start: () => `\n`,
  328. end: () => `\n`,
  329. }),
  330. createSelector({
  331. selector: 'tfoot',
  332. start: () => `\n`,
  333. end: () => `\n`,
  334. }),
  335. createSelector({
  336. selector: 'tbody',
  337. start: () => `\n`,
  338. end: () => `\n`,
  339. }),
  340. createSelector({
  341. selector: 'tr',
  342. match: element => element.nextElementSibling?.nodeName === 'TR',
  343. end: () => `\n`,
  344. }),
  345. createSelector({
  346. selector: 'tr > td:not(:last-child), tr > th:not(:last-child)',
  347. start: element => {
  348. const colspan = element.getAttribute('colspan')
  349. return colspan ? `\\multicolumn{${Number(colspan)}}{` : ''
  350. },
  351. end: element => {
  352. const colspan = element.getAttribute('colspan')
  353. return colspan ? `} & ` : ` & `
  354. },
  355. }),
  356. createSelector({
  357. selector: 'tr > td:last-child, tr > th:last-child',
  358. start: element => {
  359. const colspan = element.getAttribute('colspan')
  360. return colspan ? `\\multicolumn{${Number(colspan)}}{` : ''
  361. },
  362. end: element => {
  363. const colspan = element.getAttribute('colspan')
  364. return colspan ? `} \\\\` : ` \\\\`
  365. },
  366. }),
  367. createSelector({
  368. selector: 'caption',
  369. start: () => `\n\n\\caption{`,
  370. end: () => `}\n\n`,
  371. }),
  372. createSelector({
  373. selector: 'ul',
  374. start: element => `\n\n${listIndent(element)}\\begin{itemize}`,
  375. end: element => `\n${listIndent(element)}\\end{itemize}\n`,
  376. }),
  377. createSelector({
  378. selector: 'ol',
  379. start: element => `\n\n${listIndent(element)}\\begin{enumerate}`,
  380. end: element => `\n${listIndent(element)}\\end{enumerate}\n`,
  381. }),
  382. createSelector({
  383. selector: 'li',
  384. start: element => `\n${listIndent(element)}\t\\item `,
  385. }),
  386. createSelector({
  387. selector: 'p',
  388. match: element =>
  389. element.nextElementSibling?.nodeName === 'P' && hasContent(element),
  390. end: () => '\n\n',
  391. }),
  392. ]