paste-html.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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. // add empty cells to account for rowspan
  193. for (const cell of table.querySelectorAll<HTMLTableCellElement>(
  194. 'th[rowspan],td[rowspan]'
  195. )) {
  196. const rowspan = Number(cell.getAttribute('rowspan') || '1')
  197. const colspan = Number(cell.getAttribute('colspan') || '1')
  198. let row: HTMLTableRowElement | null = cell.closest('tr')
  199. if (row) {
  200. let position = 0
  201. for (const child of row.cells) {
  202. if (child === cell) {
  203. break
  204. }
  205. position += Number(child.getAttribute('colspan') || '1')
  206. }
  207. for (let i = 1; i < rowspan; i++) {
  208. const nextElement: Element | null = row?.nextElementSibling
  209. if (!isTableRow(nextElement)) {
  210. break
  211. }
  212. row = nextElement
  213. let targetCell: HTMLTableCellElement | undefined
  214. let targetPosition = 0
  215. for (const child of row.cells) {
  216. if (targetPosition === position) {
  217. targetCell = child
  218. break
  219. }
  220. targetPosition += Number(child.getAttribute('colspan') || '1')
  221. }
  222. const fillerCells = Array.from({ length: colspan }, () =>
  223. document.createElement('td')
  224. )
  225. if (targetCell) {
  226. targetCell.before(...fillerCells)
  227. } else {
  228. row.append(...fillerCells)
  229. }
  230. }
  231. }
  232. }
  233. }
  234. }
  235. const isTableRow = (element: Element | null): element is HTMLTableRowElement =>
  236. element?.tagName === 'TR'
  237. const cellAlignment = new Map([
  238. ['left', 'l'],
  239. ['center', 'c'],
  240. ['right', 'r'],
  241. ])
  242. const tabular = (element: HTMLTableElement) => {
  243. const definitions: Array<{
  244. alignment: string
  245. borderLeft: boolean
  246. borderRight: boolean
  247. }> = []
  248. const rows = element.querySelectorAll('tr')
  249. for (const row of rows) {
  250. const cells = [...row.childNodes].filter(
  251. element => element.nodeName === 'TD' || element.nodeName === 'TH'
  252. ) as Array<HTMLTableCellElement>
  253. let index = 0
  254. for (const cell of cells) {
  255. // NOTE: reading the alignment and borders from the first cell definition in each column
  256. if (definitions[index] === undefined) {
  257. const { textAlign, borderLeftStyle, borderRightStyle } = cell.style
  258. definitions[index] = {
  259. alignment: textAlign,
  260. borderLeft: visibleBorderStyle(borderLeftStyle),
  261. borderRight: visibleBorderStyle(borderRightStyle),
  262. }
  263. }
  264. index += Number(cell.getAttribute('colspan') ?? 1)
  265. }
  266. }
  267. for (let index = 0; index <= definitions.length; index++) {
  268. // fill in missing definitions
  269. const item = definitions[index] || {
  270. alignment: 'left',
  271. borderLeft: false,
  272. borderRight: false,
  273. }
  274. // remove left border if previous column had a right border
  275. if (item.borderLeft && index > 0 && definitions[index - 1]?.borderRight) {
  276. item.borderLeft = false
  277. }
  278. }
  279. return definitions
  280. .flatMap(definition => [
  281. definition.borderLeft ? '|' : '',
  282. cellAlignment.get(definition.alignment) ?? 'l',
  283. definition.borderRight ? '|' : '',
  284. ])
  285. .filter(Boolean)
  286. .join(' ')
  287. }
  288. const listDepth = (
  289. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  290. ): number => Math.max(0, matchingParents(element, 'ul,ol').length - 1)
  291. const listIndent = (
  292. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  293. ): string => '\t'.repeat(listDepth(element))
  294. type ElementSelector<T extends string, E extends HTMLElement = HTMLElement> = {
  295. selector: T
  296. match?: (element: E) => boolean
  297. start?: (element: E) => string
  298. end?: (element: E) => string
  299. inside?: boolean
  300. }
  301. const createSelector = <
  302. T extends string,
  303. E extends HTMLElement = T extends keyof HTMLElementTagNameMap
  304. ? HTMLElementTagNameMap[T]
  305. : HTMLElement
  306. >({
  307. selector,
  308. ...elementSelector
  309. }: ElementSelector<T, E>) => ({
  310. selector,
  311. ...elementSelector,
  312. })
  313. const headings = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']
  314. const isHeading = (element: HTMLElement | null) => {
  315. return element && headings.includes(element.nodeName)
  316. }
  317. const hasContent = (element: HTMLElement): boolean => {
  318. return Boolean(element.textContent && element.textContent.trim().length > 0)
  319. }
  320. type BorderStyle =
  321. | 'borderTopStyle'
  322. | 'borderRightStyle'
  323. | 'borderBottomStyle'
  324. | 'borderLeftStyle'
  325. const visibleBorderStyle = (style: CSSStyleDeclaration[BorderStyle]): boolean =>
  326. !!style && style !== 'none' && style !== 'hidden'
  327. const rowHasBorderStyle = (
  328. element: HTMLTableRowElement,
  329. style: BorderStyle
  330. ): boolean => {
  331. if (visibleBorderStyle(element.style[style])) {
  332. return true
  333. }
  334. const cells = element.querySelectorAll<HTMLTableCellElement>('th,td')
  335. return [...cells].every(cell => visibleBorderStyle(cell.style[style]))
  336. }
  337. const isTableRowElement = (
  338. element: Element | null
  339. ): element is HTMLTableRowElement => element?.tagName === 'TR'
  340. const nextRowHasBorderStyle = (
  341. element: HTMLTableRowElement,
  342. style: BorderStyle
  343. ) => {
  344. const { nextElementSibling } = element
  345. return (
  346. isTableRowElement(nextElementSibling) &&
  347. rowHasBorderStyle(nextElementSibling, style)
  348. )
  349. }
  350. const startMulticolumn = (element: HTMLTableCellElement): string => {
  351. const colspan = Number(element.getAttribute('colspan') || 1)
  352. const alignment = cellAlignment.get(element.style.textAlign) ?? 'l'
  353. return `\\multicolumn{${colspan}}{${alignment}}{`
  354. }
  355. const startMultirow = (element: HTMLTableCellElement): string => {
  356. const rowspan = Number(element.getAttribute('rowspan') || 1)
  357. // NOTE: it would be useful to read cell width if specified, using `*` as a starting point
  358. return `\\multirow{${rowspan}}{*}{`
  359. }
  360. const selectors = [
  361. createSelector({
  362. selector: 'b',
  363. match: element =>
  364. element.style.fontWeight !== 'normal' &&
  365. !isHeading(element.parentElement) &&
  366. hasContent(element),
  367. start: () => '\\textbf{',
  368. end: () => '}',
  369. }),
  370. createSelector({
  371. selector: '*',
  372. match: element =>
  373. parseInt(element.style.fontWeight) >= 700 && hasContent(element),
  374. start: () => '\\textbf{',
  375. end: () => '}',
  376. inside: true,
  377. }),
  378. createSelector({
  379. selector: 'strong',
  380. match: element => hasContent(element),
  381. start: () => '\\textbf{',
  382. end: () => '}',
  383. }),
  384. createSelector({
  385. selector: 'i',
  386. match: element =>
  387. element.style.fontStyle !== 'normal' && hasContent(element),
  388. start: () => '\\textit{',
  389. end: () => '}',
  390. }),
  391. createSelector({
  392. selector: '*',
  393. match: element =>
  394. element.style.fontStyle === 'italic' && hasContent(element),
  395. start: () => '\\textit{',
  396. end: () => '}',
  397. }),
  398. createSelector({
  399. selector: 'em',
  400. match: element => hasContent(element),
  401. start: () => '\\textit{',
  402. end: () => '}',
  403. }),
  404. createSelector({
  405. selector: 'sup',
  406. match: element => hasContent(element),
  407. start: () => '\\textsuperscript{',
  408. end: () => '}',
  409. }),
  410. createSelector({
  411. selector: 'span',
  412. match: element =>
  413. element.style.verticalAlign === 'super' && hasContent(element),
  414. start: () => '\\textsuperscript{',
  415. end: () => '}',
  416. }),
  417. createSelector({
  418. selector: 'sub',
  419. match: element => hasContent(element),
  420. start: () => '\\textsubscript{',
  421. end: () => '}',
  422. }),
  423. createSelector({
  424. selector: 'span',
  425. match: element =>
  426. element.style.verticalAlign === 'sub' && hasContent(element),
  427. start: () => '\\textsubscript{',
  428. end: () => '}',
  429. }),
  430. createSelector({
  431. selector: 'a',
  432. match: element => !!element.href && hasContent(element),
  433. start: (element: HTMLAnchorElement) => `\\href{${element.href}}{`,
  434. end: element => `}`,
  435. }),
  436. createSelector({
  437. selector: 'h1',
  438. match: element => !element.closest('table') && hasContent(element),
  439. start: () => `\n\n\\section{`,
  440. end: () => `}\n\n`,
  441. }),
  442. createSelector({
  443. selector: 'h2',
  444. match: element => !element.closest('table') && hasContent(element),
  445. start: () => `\n\n\\subsection{`,
  446. end: () => `}\n\n`,
  447. }),
  448. createSelector({
  449. selector: 'h3',
  450. match: element => !element.closest('table') && hasContent(element),
  451. start: () => `\n\n\\subsubsection{`,
  452. end: () => `}\n\n`,
  453. }),
  454. createSelector({
  455. selector: 'h4',
  456. match: element => !element.closest('table') && hasContent(element),
  457. start: () => `\n\n\\paragraph{`,
  458. end: () => `}\n\n`,
  459. }),
  460. createSelector({
  461. selector: 'h5',
  462. match: element => !element.closest('table') && hasContent(element),
  463. start: () => `\n\n\\subparagraph{`,
  464. end: () => `}\n\n`,
  465. }),
  466. // TODO: h6?
  467. createSelector({
  468. selector: 'br',
  469. match: element => element.parentElement?.nodeName !== 'TD', // TODO: why?
  470. start: () => `\n\n`,
  471. }),
  472. createSelector({
  473. selector: 'code',
  474. match: element =>
  475. element.parentElement?.nodeName !== 'PRE' && hasContent(element),
  476. start: () => `\\verb|`,
  477. end: () => `|`,
  478. }),
  479. createSelector({
  480. selector: 'pre > code',
  481. match: element => hasContent(element),
  482. start: () => `\n\n\\begin{verbatim}\n`,
  483. end: () => `\n\\end{verbatim}\n\n`,
  484. }),
  485. createSelector({
  486. selector: '.ol-table-wrap',
  487. start: () => `\n\n\\begin{table}\n\\centering\n`,
  488. end: () => `\n\\end{table}\n\n`,
  489. }),
  490. createSelector({
  491. selector: 'table',
  492. start: element => `\n\\begin{tabular}{${tabular(element)}}`,
  493. end: () => `\\end{tabular}\n`,
  494. }),
  495. createSelector({
  496. selector: 'thead',
  497. start: () => `\n`,
  498. end: () => `\n`,
  499. }),
  500. createSelector({
  501. selector: 'tfoot',
  502. start: () => `\n`,
  503. end: () => `\n`,
  504. }),
  505. createSelector({
  506. selector: 'tbody',
  507. start: () => `\n`,
  508. end: () => `\n`,
  509. }),
  510. createSelector({
  511. selector: 'tr',
  512. start: element => {
  513. const borderTop = rowHasBorderStyle(element, 'borderTopStyle')
  514. return borderTop ? '\\hline\n' : ''
  515. },
  516. end: element => {
  517. const borderBottom = rowHasBorderStyle(element, 'borderBottomStyle')
  518. return borderBottom && !nextRowHasBorderStyle(element, 'borderTopStyle')
  519. ? '\n\\hline\n'
  520. : '\n'
  521. },
  522. }),
  523. createSelector({
  524. selector: 'tr > td, tr > th',
  525. start: (element: HTMLTableCellElement) => {
  526. let output = ''
  527. if (element.getAttribute('colspan')) {
  528. output += startMulticolumn(element)
  529. }
  530. // NOTE: multirow is nested inside multicolumn
  531. if (element.getAttribute('rowspan')) {
  532. output += startMultirow(element)
  533. }
  534. return output
  535. },
  536. end: element => {
  537. let output = ''
  538. // NOTE: multirow is nested inside multicolumn
  539. if (element.getAttribute('rowspan')) {
  540. output += '}'
  541. }
  542. if (element.getAttribute('colspan')) {
  543. output += '}'
  544. }
  545. const row = element.parentElement as HTMLTableRowElement
  546. const isLastChild = row.cells.item(row.cells.length - 1) === element
  547. return output + (isLastChild ? ' \\\\' : ' & ')
  548. },
  549. }),
  550. createSelector({
  551. selector: 'caption',
  552. start: () => `\n\n\\caption{`,
  553. end: () => `}\n\n`,
  554. }),
  555. createSelector({
  556. selector: 'ul',
  557. start: element => `\n\n${listIndent(element)}\\begin{itemize}`,
  558. end: element => `\n${listIndent(element)}\\end{itemize}\n`,
  559. }),
  560. createSelector({
  561. selector: 'ol',
  562. start: element => `\n\n${listIndent(element)}\\begin{enumerate}`,
  563. end: element => `\n${listIndent(element)}\\end{enumerate}\n`,
  564. }),
  565. createSelector({
  566. selector: 'li',
  567. start: element => `\n${listIndent(element)}\t\\item `,
  568. }),
  569. createSelector({
  570. selector: 'p',
  571. match: element => {
  572. // must have content
  573. if (!hasContent(element)) {
  574. return false
  575. }
  576. // inside lists and tables, must precede another paragraph
  577. if (element.closest('li') || element.closest('table')) {
  578. return element.nextElementSibling?.nodeName === 'P'
  579. }
  580. return true
  581. },
  582. end: () => '\n\n',
  583. }),
  584. createSelector({
  585. selector: 'blockquote',
  586. start: () => `\n\n\\begin{quote}\n`,
  587. end: () => `\n\\end{quote}\n\n`,
  588. }),
  589. ]