paste-html.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. // pre-process lists
  83. processLists(documentElement)
  84. // protect special characters in non-LaTeX text nodes
  85. protectSpecialCharacters(documentElement)
  86. processMatchedElements(documentElement)
  87. const text = documentElement.textContent
  88. if (!text) {
  89. return ''
  90. }
  91. // normalise multiple newlines
  92. return text.replaceAll(/\n{2,}/g, '\n\n')
  93. }
  94. const processWhitespace = (documentElement: HTMLElement) => {
  95. const walker = document.createTreeWalker(
  96. documentElement,
  97. NodeFilter.SHOW_TEXT
  98. )
  99. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  100. if (node.textContent === ' ') {
  101. node.textContent = ' '
  102. }
  103. }
  104. }
  105. const isElementNode = (node: Node): node is HTMLElement =>
  106. node.nodeType === Node.ELEMENT_NODE
  107. // TODO: negative lookbehind once Safari supports it
  108. const specialCharacterRegExp = /(^|[^\\])([#$%&~_^\\{}])/g
  109. const specialCharacterReplacer = (
  110. _match: string,
  111. prefix: string,
  112. char: string
  113. ) => {
  114. if (char === '\\') {
  115. // convert `\` to `\textbackslash{}`, preserving subsequent whitespace
  116. char = 'textbackslash{}'
  117. }
  118. return `${prefix}\\${char}`
  119. }
  120. const protectSpecialCharacters = (documentElement: HTMLElement) => {
  121. const walker = document.createTreeWalker(
  122. documentElement,
  123. NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
  124. node =>
  125. isElementNode(node) && node.tagName === 'CODE'
  126. ? NodeFilter.FILTER_REJECT
  127. : NodeFilter.FILTER_ACCEPT
  128. )
  129. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  130. if (node.nodeType === Node.TEXT_NODE) {
  131. const text = node.textContent
  132. if (text) {
  133. // replace non-backslash-prefixed characters
  134. node.textContent = text.replaceAll(
  135. specialCharacterRegExp,
  136. specialCharacterReplacer
  137. )
  138. }
  139. }
  140. }
  141. }
  142. const processMatchedElements = (documentElement: HTMLElement) => {
  143. for (const item of selectors) {
  144. for (const element of documentElement.querySelectorAll<any>(
  145. item.selector
  146. )) {
  147. if (!item.match || item.match(element)) {
  148. // start the markup
  149. if (item.start) {
  150. const start = document.createTextNode(item.start(element))
  151. if (item.inside) {
  152. element.prepend(start)
  153. } else {
  154. element.before(start)
  155. }
  156. }
  157. // end the markup
  158. if (item.end) {
  159. const end = document.createTextNode(item.end(element))
  160. if (item.inside) {
  161. element.append(end)
  162. } else {
  163. element.after(end)
  164. }
  165. }
  166. }
  167. }
  168. }
  169. }
  170. const matchingParents = (element: HTMLElement, selector: string) => {
  171. const matches = []
  172. for (
  173. let ancestor = element.parentElement?.closest(selector);
  174. ancestor;
  175. ancestor = ancestor.parentElement?.closest(selector)
  176. ) {
  177. matches.push(ancestor)
  178. }
  179. return matches
  180. }
  181. const processLists = (element: HTMLElement) => {
  182. for (const list of element.querySelectorAll('ol,ul')) {
  183. // if the list has only one item, replace the list with an element containing the contents of the item
  184. if (list.childElementCount === 1) {
  185. const div = document.createElement('div')
  186. div.append(...list.firstElementChild!.childNodes)
  187. list.before('\n', div, '\n')
  188. list.remove()
  189. }
  190. }
  191. }
  192. const processTables = (element: HTMLElement) => {
  193. for (const table of element.querySelectorAll('table')) {
  194. // create a wrapper element for the table and the caption
  195. const container = document.createElement('div')
  196. container.className = 'ol-table-wrap'
  197. table.after(container)
  198. // move the caption (if it exists) into the container before the table
  199. const caption = table.querySelector('caption')
  200. if (caption) {
  201. container.append(caption)
  202. }
  203. // move the table into the container
  204. container.append(table)
  205. // add empty cells to account for rowspan
  206. for (const cell of table.querySelectorAll<HTMLTableCellElement>(
  207. 'th[rowspan],td[rowspan]'
  208. )) {
  209. const rowspan = Number(cell.getAttribute('rowspan') || '1')
  210. const colspan = Number(cell.getAttribute('colspan') || '1')
  211. let row: HTMLTableRowElement | null = cell.closest('tr')
  212. if (row) {
  213. let position = 0
  214. for (const child of row.cells) {
  215. if (child === cell) {
  216. break
  217. }
  218. position += Number(child.getAttribute('colspan') || '1')
  219. }
  220. for (let i = 1; i < rowspan; i++) {
  221. const nextElement: Element | null = row?.nextElementSibling
  222. if (!isTableRow(nextElement)) {
  223. break
  224. }
  225. row = nextElement
  226. let targetCell: HTMLTableCellElement | undefined
  227. let targetPosition = 0
  228. for (const child of row.cells) {
  229. if (targetPosition === position) {
  230. targetCell = child
  231. break
  232. }
  233. targetPosition += Number(child.getAttribute('colspan') || '1')
  234. }
  235. const fillerCells = Array.from({ length: colspan }, () =>
  236. document.createElement('td')
  237. )
  238. if (targetCell) {
  239. targetCell.before(...fillerCells)
  240. } else {
  241. row.append(...fillerCells)
  242. }
  243. }
  244. }
  245. }
  246. }
  247. }
  248. const isTableRow = (element: Element | null): element is HTMLTableRowElement =>
  249. element?.tagName === 'TR'
  250. const cellAlignment = new Map([
  251. ['left', 'l'],
  252. ['center', 'c'],
  253. ['right', 'r'],
  254. ])
  255. const tabular = (element: HTMLTableElement) => {
  256. const definitions: Array<{
  257. alignment: string
  258. borderLeft: boolean
  259. borderRight: boolean
  260. }> = []
  261. const rows = element.querySelectorAll('tr')
  262. for (const row of rows) {
  263. const cells = [...row.childNodes].filter(
  264. element => element.nodeName === 'TD' || element.nodeName === 'TH'
  265. ) as Array<HTMLTableCellElement>
  266. let index = 0
  267. for (const cell of cells) {
  268. // NOTE: reading the alignment and borders from the first cell definition in each column
  269. if (definitions[index] === undefined) {
  270. const { textAlign, borderLeftStyle, borderRightStyle } = cell.style
  271. definitions[index] = {
  272. alignment: textAlign,
  273. borderLeft: visibleBorderStyle(borderLeftStyle),
  274. borderRight: visibleBorderStyle(borderRightStyle),
  275. }
  276. }
  277. index += Number(cell.getAttribute('colspan') ?? 1)
  278. }
  279. }
  280. for (let index = 0; index <= definitions.length; index++) {
  281. // fill in missing definitions
  282. const item = definitions[index] || {
  283. alignment: 'left',
  284. borderLeft: false,
  285. borderRight: false,
  286. }
  287. // remove left border if previous column had a right border
  288. if (item.borderLeft && index > 0 && definitions[index - 1]?.borderRight) {
  289. item.borderLeft = false
  290. }
  291. }
  292. return definitions
  293. .flatMap(definition => [
  294. definition.borderLeft ? '|' : '',
  295. cellAlignment.get(definition.alignment) ?? 'l',
  296. definition.borderRight ? '|' : '',
  297. ])
  298. .filter(Boolean)
  299. .join(' ')
  300. }
  301. const listDepth = (
  302. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  303. ): number => Math.max(0, matchingParents(element, 'ul,ol').length - 1)
  304. const listIndent = (
  305. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  306. ): string => '\t'.repeat(listDepth(element))
  307. type ElementSelector<T extends string, E extends HTMLElement = HTMLElement> = {
  308. selector: T
  309. match?: (element: E) => boolean
  310. start?: (element: E) => string
  311. end?: (element: E) => string
  312. inside?: boolean
  313. }
  314. const createSelector = <
  315. T extends string,
  316. E extends HTMLElement = T extends keyof HTMLElementTagNameMap
  317. ? HTMLElementTagNameMap[T]
  318. : HTMLElement
  319. >({
  320. selector,
  321. ...elementSelector
  322. }: ElementSelector<T, E>) => ({
  323. selector,
  324. ...elementSelector,
  325. })
  326. const headings = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']
  327. const isHeading = (element: HTMLElement | null) => {
  328. return element && headings.includes(element.nodeName)
  329. }
  330. const hasContent = (element: HTMLElement): boolean => {
  331. return Boolean(element.textContent && element.textContent.trim().length > 0)
  332. }
  333. type BorderStyle =
  334. | 'borderTopStyle'
  335. | 'borderRightStyle'
  336. | 'borderBottomStyle'
  337. | 'borderLeftStyle'
  338. const visibleBorderStyle = (style: CSSStyleDeclaration[BorderStyle]): boolean =>
  339. !!style && style !== 'none' && style !== 'hidden'
  340. const rowHasBorderStyle = (
  341. element: HTMLTableRowElement,
  342. style: BorderStyle
  343. ): boolean => {
  344. if (visibleBorderStyle(element.style[style])) {
  345. return true
  346. }
  347. const cells = element.querySelectorAll<HTMLTableCellElement>('th,td')
  348. return [...cells].every(cell => visibleBorderStyle(cell.style[style]))
  349. }
  350. const isTableRowElement = (
  351. element: Element | null
  352. ): element is HTMLTableRowElement => element?.tagName === 'TR'
  353. const nextRowHasBorderStyle = (
  354. element: HTMLTableRowElement,
  355. style: BorderStyle
  356. ) => {
  357. const { nextElementSibling } = element
  358. return (
  359. isTableRowElement(nextElementSibling) &&
  360. rowHasBorderStyle(nextElementSibling, style)
  361. )
  362. }
  363. const startMulticolumn = (element: HTMLTableCellElement): string => {
  364. const colspan = Number(element.getAttribute('colspan') || 1)
  365. const alignment = cellAlignment.get(element.style.textAlign) ?? 'l'
  366. return `\\multicolumn{${colspan}}{${alignment}}{`
  367. }
  368. const startMultirow = (element: HTMLTableCellElement): string => {
  369. const rowspan = Number(element.getAttribute('rowspan') || 1)
  370. // NOTE: it would be useful to read cell width if specified, using `*` as a starting point
  371. return `\\multirow{${rowspan}}{*}{`
  372. }
  373. const selectors = [
  374. createSelector({
  375. selector: 'b',
  376. match: element =>
  377. !element.style.fontWeight &&
  378. !isHeading(element.parentElement) &&
  379. hasContent(element),
  380. start: () => '\\textbf{',
  381. end: () => '}',
  382. }),
  383. createSelector({
  384. selector: '*',
  385. match: element =>
  386. (element.style.fontWeight === 'bold' ||
  387. parseInt(element.style.fontWeight) >= 700) &&
  388. hasContent(element),
  389. start: () => '\\textbf{',
  390. end: () => '}',
  391. inside: true,
  392. }),
  393. createSelector({
  394. selector: 'strong',
  395. match: element => !element.style.fontWeight && hasContent(element),
  396. start: () => '\\textbf{',
  397. end: () => '}',
  398. }),
  399. createSelector({
  400. selector: 'i',
  401. match: element => !element.style.fontStyle && hasContent(element),
  402. start: () => '\\textit{',
  403. end: () => '}',
  404. }),
  405. createSelector({
  406. selector: '*',
  407. match: element =>
  408. element.style.fontStyle === 'italic' && hasContent(element),
  409. start: () => '\\textit{',
  410. end: () => '}',
  411. }),
  412. createSelector({
  413. selector: 'em',
  414. match: element => !element.style.fontStyle && hasContent(element),
  415. start: () => '\\textit{',
  416. end: () => '}',
  417. }),
  418. createSelector({
  419. selector: 'sup',
  420. match: element => !element.style.verticalAlign && hasContent(element),
  421. start: () => '\\textsuperscript{',
  422. end: () => '}',
  423. }),
  424. createSelector({
  425. selector: 'span',
  426. match: element =>
  427. element.style.verticalAlign === 'super' && hasContent(element),
  428. start: () => '\\textsuperscript{',
  429. end: () => '}',
  430. }),
  431. createSelector({
  432. selector: 'sub',
  433. match: element => !element.style.verticalAlign && hasContent(element),
  434. start: () => '\\textsubscript{',
  435. end: () => '}',
  436. }),
  437. createSelector({
  438. selector: 'span',
  439. match: element =>
  440. element.style.verticalAlign === 'sub' && hasContent(element),
  441. start: () => '\\textsubscript{',
  442. end: () => '}',
  443. }),
  444. createSelector({
  445. selector: 'a',
  446. match: element => !!element.href && hasContent(element),
  447. start: (element: HTMLAnchorElement) => `\\href{${element.href}}{`,
  448. end: element => `}`,
  449. }),
  450. createSelector({
  451. selector: 'h1',
  452. match: element => !element.closest('table') && hasContent(element),
  453. start: () => `\n\n\\section{`,
  454. end: () => `}\n\n`,
  455. }),
  456. createSelector({
  457. selector: 'h2',
  458. match: element => !element.closest('table') && hasContent(element),
  459. start: () => `\n\n\\subsection{`,
  460. end: () => `}\n\n`,
  461. }),
  462. createSelector({
  463. selector: 'h3',
  464. match: element => !element.closest('table') && hasContent(element),
  465. start: () => `\n\n\\subsubsection{`,
  466. end: () => `}\n\n`,
  467. }),
  468. createSelector({
  469. selector: 'h4',
  470. match: element => !element.closest('table') && hasContent(element),
  471. start: () => `\n\n\\paragraph{`,
  472. end: () => `}\n\n`,
  473. }),
  474. createSelector({
  475. selector: 'h5',
  476. match: element => !element.closest('table') && hasContent(element),
  477. start: () => `\n\n\\subparagraph{`,
  478. end: () => `}\n\n`,
  479. }),
  480. // TODO: h6?
  481. createSelector({
  482. selector: 'br',
  483. match: element => element.parentElement?.nodeName !== 'TD', // TODO: why?
  484. start: () => `\n\n`,
  485. }),
  486. createSelector({
  487. selector: 'code',
  488. match: element =>
  489. element.parentElement?.nodeName !== 'PRE' && hasContent(element),
  490. start: () => `\\verb|`,
  491. end: () => `|`,
  492. }),
  493. createSelector({
  494. selector: 'pre > code',
  495. match: element => hasContent(element),
  496. start: () => `\n\n\\begin{verbatim}\n`,
  497. end: () => `\n\\end{verbatim}\n\n`,
  498. }),
  499. createSelector({
  500. selector: '.ol-table-wrap',
  501. start: () => `\n\n\\begin{table}\n\\centering\n`,
  502. end: () => `\n\\end{table}\n\n`,
  503. }),
  504. createSelector({
  505. selector: 'table',
  506. start: element => `\n\\begin{tabular}{${tabular(element)}}`,
  507. end: () => `\\end{tabular}\n`,
  508. }),
  509. createSelector({
  510. selector: 'thead',
  511. start: () => `\n`,
  512. end: () => `\n`,
  513. }),
  514. createSelector({
  515. selector: 'tfoot',
  516. start: () => `\n`,
  517. end: () => `\n`,
  518. }),
  519. createSelector({
  520. selector: 'tbody',
  521. start: () => `\n`,
  522. end: () => `\n`,
  523. }),
  524. createSelector({
  525. selector: 'tr',
  526. start: element => {
  527. const borderTop = rowHasBorderStyle(element, 'borderTopStyle')
  528. return borderTop ? '\\hline\n' : ''
  529. },
  530. end: element => {
  531. const borderBottom = rowHasBorderStyle(element, 'borderBottomStyle')
  532. return borderBottom && !nextRowHasBorderStyle(element, 'borderTopStyle')
  533. ? '\n\\hline\n'
  534. : '\n'
  535. },
  536. }),
  537. createSelector({
  538. selector: 'tr > td, tr > th',
  539. start: (element: HTMLTableCellElement) => {
  540. let output = ''
  541. if (element.getAttribute('colspan')) {
  542. output += startMulticolumn(element)
  543. }
  544. // NOTE: multirow is nested inside multicolumn
  545. if (element.getAttribute('rowspan')) {
  546. output += startMultirow(element)
  547. }
  548. return output
  549. },
  550. end: element => {
  551. let output = ''
  552. // NOTE: multirow is nested inside multicolumn
  553. if (element.getAttribute('rowspan')) {
  554. output += '}'
  555. }
  556. if (element.getAttribute('colspan')) {
  557. output += '}'
  558. }
  559. const row = element.parentElement as HTMLTableRowElement
  560. const isLastChild = row.cells.item(row.cells.length - 1) === element
  561. return output + (isLastChild ? ' \\\\' : ' & ')
  562. },
  563. }),
  564. createSelector({
  565. selector: 'caption',
  566. start: () => `\n\n\\caption{`,
  567. end: () => `}\n\n`,
  568. }),
  569. createSelector({
  570. // selector: 'ul:has(> li:nth-child(2))', // only select lists with at least 2 items (once Firefox supports :has())
  571. selector: 'ul',
  572. start: element => `\n\n${listIndent(element)}\\begin{itemize}`,
  573. end: element => `\n${listIndent(element)}\\end{itemize}\n`,
  574. }),
  575. createSelector({
  576. // selector: 'ol:has(> li:nth-child(2))', // only select lists with at least 2 items (once Firefox supports :has())
  577. selector: 'ol',
  578. start: element => `\n\n${listIndent(element)}\\begin{enumerate}`,
  579. end: element => `\n${listIndent(element)}\\end{enumerate}\n`,
  580. }),
  581. createSelector({
  582. selector: 'li',
  583. start: element => `\n${listIndent(element)}\t\\item `,
  584. }),
  585. createSelector({
  586. selector: 'p',
  587. match: element => {
  588. // must have content
  589. if (!hasContent(element)) {
  590. return false
  591. }
  592. // inside lists and tables, must precede another paragraph
  593. if (element.closest('li') || element.closest('table')) {
  594. return element.nextElementSibling?.nodeName === 'P'
  595. }
  596. return true
  597. },
  598. end: () => '\n\n',
  599. }),
  600. createSelector({
  601. selector: 'blockquote',
  602. start: () => `\n\n\\begin{quote}\n`,
  603. end: () => `\n\\end{quote}\n\n`,
  604. }),
  605. ]