paste-html.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. import { EditorView } from '@codemirror/view'
  2. import { Prec } from '@codemirror/state'
  3. import {
  4. insertPastedContent,
  5. pastedContent,
  6. storePastedContent,
  7. } from './pasted-content'
  8. export const pasteHtml = [
  9. Prec.highest(
  10. EditorView.domEventHandlers({
  11. paste(event, view) {
  12. const { clipboardData } = event
  13. if (!clipboardData) {
  14. return false
  15. }
  16. // allow pasting an image to create a figure
  17. if (clipboardData.files.length > 0) {
  18. return false
  19. }
  20. // only handle pasted HTML
  21. if (!clipboardData.types.includes('text/html')) {
  22. return false
  23. }
  24. // ignore text/html from VS Code
  25. if (
  26. clipboardData.types.includes('application/vnd.code.copymetadata') ||
  27. clipboardData.types.includes('vscode-editor-data')
  28. ) {
  29. return false
  30. }
  31. const html = clipboardData.getData('text/html').trim()
  32. const text = clipboardData.getData('text/plain').trim()
  33. if (html.length === 0) {
  34. return false
  35. }
  36. // convert the HTML to LaTeX
  37. try {
  38. const parser = new DOMParser()
  39. const { documentElement } = parser.parseFromString(html, 'text/html')
  40. // if the only content is in a code block, use the plain text version
  41. if (onlyCode(documentElement)) {
  42. return false
  43. }
  44. const latex = htmlToLaTeX(documentElement)
  45. // if there's no formatting, use the plain text version
  46. if (latex === text) {
  47. return false
  48. }
  49. view.dispatch(insertPastedContent(view, { latex, text }))
  50. view.dispatch(storePastedContent({ latex, text }, true))
  51. return true
  52. } catch (error) {
  53. console.error(error)
  54. // fall back to the default paste handler
  55. return false
  56. }
  57. },
  58. })
  59. ),
  60. pastedContent,
  61. ]
  62. const removeUnwantedElements = (
  63. documentElement: HTMLElement,
  64. selector: string
  65. ) => {
  66. for (const element of documentElement.querySelectorAll(selector)) {
  67. element.remove()
  68. }
  69. }
  70. // return true if the text content of the first <code> element
  71. // is the same as the text content of the whole document element
  72. const onlyCode = (documentElement: HTMLElement) =>
  73. documentElement.querySelector('code')?.textContent?.trim() ===
  74. documentElement.textContent?.trim()
  75. const htmlToLaTeX = (documentElement: HTMLElement) => {
  76. // remove style elements
  77. removeUnwantedElements(documentElement, 'style')
  78. // replace non-breaking spaces added by Chrome on copy
  79. processWhitespace(documentElement)
  80. // pre-process table elements
  81. processTables(documentElement)
  82. // protect special characters in non-LaTeX text nodes
  83. protectSpecialCharacters(documentElement)
  84. processMatchedElements(documentElement)
  85. const text = documentElement.textContent
  86. if (!text) {
  87. return ''
  88. }
  89. // normalise multiple newlines
  90. return text.replaceAll(/\n{2,}/g, '\n\n')
  91. }
  92. const processWhitespace = (documentElement: HTMLElement) => {
  93. const walker = document.createTreeWalker(
  94. documentElement,
  95. NodeFilter.SHOW_TEXT
  96. )
  97. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  98. if (node.textContent === ' ') {
  99. node.textContent = ' '
  100. }
  101. }
  102. }
  103. const isElementNode = (node: Node): node is HTMLElement =>
  104. node.nodeType === Node.ELEMENT_NODE
  105. // TODO: negative lookbehind once Safari supports it
  106. const specialCharacterRegExp = /(^|[^\\])([#$%&~_^\\{}])/g
  107. const specialCharacterReplacer = (
  108. _match: string,
  109. prefix: string,
  110. char: string
  111. ) => {
  112. if (char === '\\') {
  113. // convert `\` to `\textbackslash{}`, preserving subsequent whitespace
  114. char = 'textbackslash{}'
  115. }
  116. return `${prefix}\\${char}`
  117. }
  118. const protectSpecialCharacters = (documentElement: HTMLElement) => {
  119. const walker = document.createTreeWalker(
  120. documentElement,
  121. NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
  122. node =>
  123. isElementNode(node) && node.tagName === 'CODE'
  124. ? NodeFilter.FILTER_REJECT
  125. : NodeFilter.FILTER_ACCEPT
  126. )
  127. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  128. if (node.nodeType === Node.TEXT_NODE) {
  129. const text = node.textContent
  130. if (text) {
  131. // replace non-backslash-prefixed characters
  132. node.textContent = text.replaceAll(
  133. specialCharacterRegExp,
  134. specialCharacterReplacer
  135. )
  136. }
  137. }
  138. }
  139. }
  140. const processMatchedElements = (documentElement: HTMLElement) => {
  141. for (const item of selectors) {
  142. for (const element of documentElement.querySelectorAll<any>(
  143. item.selector
  144. )) {
  145. if (!item.match || item.match(element)) {
  146. // start the markup
  147. if (item.start) {
  148. const start = document.createTextNode(item.start(element))
  149. if (item.inside) {
  150. element.prepend(start)
  151. } else {
  152. element.before(start)
  153. }
  154. }
  155. // end the markup
  156. if (item.end) {
  157. const end = document.createTextNode(item.end(element))
  158. if (item.inside) {
  159. element.append(end)
  160. } else {
  161. element.after(end)
  162. }
  163. }
  164. }
  165. }
  166. }
  167. }
  168. const matchingParents = (element: HTMLElement, selector: string) => {
  169. const matches = []
  170. for (
  171. let ancestor = element.parentElement?.closest(selector);
  172. ancestor;
  173. ancestor = ancestor.parentElement?.closest(selector)
  174. ) {
  175. matches.push(ancestor)
  176. }
  177. return matches
  178. }
  179. const processTables = (element: HTMLElement) => {
  180. for (const table of element.querySelectorAll('table')) {
  181. // create a wrapper element for the table and the caption
  182. const container = document.createElement('div')
  183. container.className = 'ol-table-wrap'
  184. table.after(container)
  185. // move the caption (if it exists) into the container before the table
  186. const caption = table.querySelector('caption')
  187. if (caption) {
  188. container.append(caption)
  189. }
  190. // move the table into the container
  191. container.append(table)
  192. }
  193. }
  194. const cellAlignment = new Map([
  195. ['left', 'l'],
  196. ['center', 'c'],
  197. ['right', 'r'],
  198. ])
  199. const tabular = (element: HTMLTableElement) => {
  200. const definitions: Array<{
  201. alignment: string
  202. borderLeft: boolean
  203. borderRight: boolean
  204. }> = []
  205. const rows = element.querySelectorAll('tr')
  206. for (const row of rows) {
  207. const cells = [...row.childNodes].filter(
  208. element => element.nodeName === 'TD' || element.nodeName === 'TH'
  209. ) as Array<HTMLTableCellElement>
  210. let index = 0
  211. for (const cell of cells) {
  212. // NOTE: reading the alignment and borders from the first cell definition in each column
  213. if (definitions[index] === undefined) {
  214. const { textAlign, borderLeftStyle, borderRightStyle } = cell.style
  215. definitions[index] = {
  216. alignment: textAlign,
  217. borderLeft: visibleBorderStyle(borderLeftStyle),
  218. borderRight: visibleBorderStyle(borderRightStyle),
  219. }
  220. }
  221. index += Number(cell.getAttribute('colspan') ?? 1)
  222. }
  223. }
  224. for (let index = 0; index <= definitions.length; index++) {
  225. // fill in missing definitions
  226. const item = definitions[index] || {
  227. alignment: 'left',
  228. borderLeft: false,
  229. borderRight: false,
  230. }
  231. // remove left border if previous column had a right border
  232. if (item.borderLeft && index > 0 && definitions[index - 1]?.borderRight) {
  233. item.borderLeft = false
  234. }
  235. }
  236. return definitions
  237. .flatMap(definition => [
  238. definition.borderLeft ? '|' : '',
  239. cellAlignment.get(definition.alignment) ?? 'l',
  240. definition.borderRight ? '|' : '',
  241. ])
  242. .filter(Boolean)
  243. .join(' ')
  244. }
  245. const listDepth = (
  246. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  247. ): number => Math.max(0, matchingParents(element, 'ul,ol').length - 1)
  248. const listIndent = (
  249. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  250. ): string => '\t'.repeat(listDepth(element))
  251. type ElementSelector<T extends string, E extends HTMLElement = HTMLElement> = {
  252. selector: T
  253. match?: (element: E) => boolean
  254. start?: (element: E) => string
  255. end?: (element: E) => string
  256. inside?: boolean
  257. }
  258. const createSelector = <
  259. T extends string,
  260. E extends HTMLElement = T extends keyof HTMLElementTagNameMap
  261. ? HTMLElementTagNameMap[T]
  262. : HTMLElement
  263. >({
  264. selector,
  265. ...elementSelector
  266. }: ElementSelector<T, E>) => ({
  267. selector,
  268. ...elementSelector,
  269. })
  270. const headings = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']
  271. const isHeading = (element: HTMLElement | null) => {
  272. return element && headings.includes(element.nodeName)
  273. }
  274. const hasContent = (element: HTMLElement): boolean => {
  275. return Boolean(element.textContent && element.textContent.trim().length > 0)
  276. }
  277. type BorderStyle =
  278. | 'borderTopStyle'
  279. | 'borderRightStyle'
  280. | 'borderBottomStyle'
  281. | 'borderLeftStyle'
  282. const visibleBorderStyle = (style: CSSStyleDeclaration[BorderStyle]): boolean =>
  283. !!style && style !== 'none' && style !== 'hidden'
  284. const rowHasBorderStyle = (
  285. element: HTMLTableRowElement,
  286. style: BorderStyle
  287. ): boolean => {
  288. if (visibleBorderStyle(element.style[style])) {
  289. return true
  290. }
  291. const cells = element.querySelectorAll<HTMLTableCellElement>('th,td')
  292. return [...cells].every(cell => visibleBorderStyle(cell.style[style]))
  293. }
  294. const isTableRowElement = (
  295. element: Element | null
  296. ): element is HTMLTableRowElement => element?.tagName === 'TR'
  297. const nextRowHasBorderStyle = (
  298. element: HTMLTableRowElement,
  299. style: BorderStyle
  300. ) => {
  301. const { nextElementSibling } = element
  302. return (
  303. isTableRowElement(nextElementSibling) &&
  304. rowHasBorderStyle(nextElementSibling, style)
  305. )
  306. }
  307. const startMulticolumn = (element: HTMLTableCellElement): string => {
  308. const colspan = element.getAttribute('colspan') ?? 1
  309. const alignment = cellAlignment.get(element.style.textAlign) ?? 'l'
  310. return `\\multicolumn{${Number(colspan)}}{${alignment}}{`
  311. }
  312. const selectors = [
  313. createSelector({
  314. selector: 'b',
  315. match: element =>
  316. element.style.fontWeight !== 'normal' &&
  317. !isHeading(element.parentElement) &&
  318. hasContent(element),
  319. start: () => '\\textbf{',
  320. end: () => '}',
  321. }),
  322. createSelector({
  323. selector: '*',
  324. match: element =>
  325. parseInt(element.style.fontWeight) > 400 && hasContent(element),
  326. start: () => '\\textbf{',
  327. end: () => '}',
  328. inside: true,
  329. }),
  330. createSelector({
  331. selector: 'strong',
  332. match: element => hasContent(element),
  333. start: () => '\\textbf{',
  334. end: () => '}',
  335. }),
  336. createSelector({
  337. selector: 'i',
  338. match: element =>
  339. element.style.fontStyle !== 'normal' && hasContent(element),
  340. start: () => '\\textit{',
  341. end: () => '}',
  342. }),
  343. createSelector({
  344. selector: '*',
  345. match: element =>
  346. element.style.fontStyle === 'italic' && hasContent(element),
  347. start: () => '\\textit{',
  348. end: () => '}',
  349. }),
  350. createSelector({
  351. selector: 'em',
  352. match: element => hasContent(element),
  353. start: () => '\\textit{',
  354. end: () => '}',
  355. }),
  356. createSelector({
  357. selector: 'sup',
  358. match: element => hasContent(element),
  359. start: () => '\\textsuperscript{',
  360. end: () => '}',
  361. }),
  362. createSelector({
  363. selector: 'span',
  364. match: element =>
  365. element.style.verticalAlign === 'super' && hasContent(element),
  366. start: () => '\\textsuperscript{',
  367. end: () => '}',
  368. }),
  369. createSelector({
  370. selector: 'sub',
  371. match: element => hasContent(element),
  372. start: () => '\\textsubscript{',
  373. end: () => '}',
  374. }),
  375. createSelector({
  376. selector: 'span',
  377. match: element =>
  378. element.style.verticalAlign === 'sub' && hasContent(element),
  379. start: () => '\\textsubscript{',
  380. end: () => '}',
  381. }),
  382. createSelector({
  383. selector: 'a',
  384. match: element => !!element.href && hasContent(element),
  385. start: (element: HTMLAnchorElement) => `\\href{${element.href}}{`,
  386. end: element => `}`,
  387. }),
  388. createSelector({
  389. selector: 'h1',
  390. match: element => !element.closest('table') && hasContent(element),
  391. start: () => `\n\n\\section{`,
  392. end: () => `}\n\n`,
  393. }),
  394. createSelector({
  395. selector: 'h2',
  396. match: element => !element.closest('table') && hasContent(element),
  397. start: () => `\n\n\\subsection{`,
  398. end: () => `}\n\n`,
  399. }),
  400. createSelector({
  401. selector: 'h3',
  402. match: element => !element.closest('table') && hasContent(element),
  403. start: () => `\n\n\\subsubsection{`,
  404. end: () => `}\n\n`,
  405. }),
  406. createSelector({
  407. selector: 'h4',
  408. match: element => !element.closest('table') && hasContent(element),
  409. start: () => `\n\n\\paragraph{`,
  410. end: () => `}\n\n`,
  411. }),
  412. createSelector({
  413. selector: 'h5',
  414. match: element => !element.closest('table') && hasContent(element),
  415. start: () => `\n\n\\subparagraph{`,
  416. end: () => `}\n\n`,
  417. }),
  418. // TODO: h6?
  419. createSelector({
  420. selector: 'br',
  421. match: element => element.parentElement?.nodeName !== 'TD', // TODO: why?
  422. start: () => `\n\n`,
  423. }),
  424. createSelector({
  425. selector: 'code',
  426. match: element =>
  427. element.parentElement?.nodeName !== 'PRE' && hasContent(element),
  428. start: () => `\\verb|`,
  429. end: () => `|`,
  430. }),
  431. createSelector({
  432. selector: 'pre > code',
  433. match: element => hasContent(element),
  434. start: () => `\n\n\\begin{verbatim}\n`,
  435. end: () => `\n\\end{verbatim}\n\n`,
  436. }),
  437. createSelector({
  438. selector: '.ol-table-wrap',
  439. start: () => `\n\n\\begin{table}\n\\centering\n`,
  440. end: () => `\n\\end{table}\n\n`,
  441. }),
  442. createSelector({
  443. selector: 'table',
  444. start: element => `\n\\begin{tabular}{${tabular(element)}}`,
  445. end: () => `\\end{tabular}\n`,
  446. }),
  447. createSelector({
  448. selector: 'thead',
  449. start: () => `\n`,
  450. end: () => `\n`,
  451. }),
  452. createSelector({
  453. selector: 'tfoot',
  454. start: () => `\n`,
  455. end: () => `\n`,
  456. }),
  457. createSelector({
  458. selector: 'tbody',
  459. start: () => `\n`,
  460. end: () => `\n`,
  461. }),
  462. createSelector({
  463. selector: 'tr',
  464. start: element => {
  465. const borderTop = rowHasBorderStyle(element, 'borderTopStyle')
  466. return borderTop ? '\\hline\n' : ''
  467. },
  468. end: element => {
  469. const borderBottom = rowHasBorderStyle(element, 'borderBottomStyle')
  470. return borderBottom && !nextRowHasBorderStyle(element, 'borderTopStyle')
  471. ? '\n\\hline\n'
  472. : '\n'
  473. },
  474. }),
  475. createSelector({
  476. selector: 'tr > td:not(:last-child), tr > th:not(:last-child)',
  477. start: (element: HTMLTableCellElement) => {
  478. const colspan = element.getAttribute('colspan')
  479. return colspan ? startMulticolumn(element) : ''
  480. },
  481. end: element => {
  482. const colspan = element.getAttribute('colspan')
  483. return colspan ? `} & ` : ` & `
  484. },
  485. }),
  486. createSelector({
  487. selector: 'tr > td:last-child, tr > th:last-child',
  488. start: (element: HTMLTableCellElement) => {
  489. const colspan = element.getAttribute('colspan')
  490. return colspan ? startMulticolumn(element) : ''
  491. },
  492. end: element => {
  493. const colspan = element.getAttribute('colspan')
  494. return colspan ? `} \\\\` : ` \\\\`
  495. },
  496. }),
  497. createSelector({
  498. selector: 'caption',
  499. start: () => `\n\n\\caption{`,
  500. end: () => `}\n\n`,
  501. }),
  502. createSelector({
  503. selector: 'ul',
  504. start: element => `\n\n${listIndent(element)}\\begin{itemize}`,
  505. end: element => `\n${listIndent(element)}\\end{itemize}\n`,
  506. }),
  507. createSelector({
  508. selector: 'ol',
  509. start: element => `\n\n${listIndent(element)}\\begin{enumerate}`,
  510. end: element => `\n${listIndent(element)}\\end{enumerate}\n`,
  511. }),
  512. createSelector({
  513. selector: 'li',
  514. start: element => `\n${listIndent(element)}\t\\item `,
  515. }),
  516. createSelector({
  517. selector: 'p',
  518. match: element => {
  519. // must have content
  520. if (!hasContent(element)) {
  521. return false
  522. }
  523. // inside lists and tables, must precede another paragraph
  524. if (element.closest('li') || element.closest('table')) {
  525. return element.nextElementSibling?.nodeName === 'P'
  526. }
  527. return true
  528. },
  529. end: () => '\n\n',
  530. }),
  531. createSelector({
  532. selector: 'blockquote',
  533. start: () => `\n\n\\begin{quote}\n`,
  534. end: () => `\n\\end{quote}\n\n`,
  535. }),
  536. ]