paste-html.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. processMatchedElements(documentElement)
  83. const text = documentElement.textContent
  84. if (!text) {
  85. return ''
  86. }
  87. // normalise multiple newlines
  88. return text.replaceAll(/\n{2,}/g, '\n\n')
  89. }
  90. const processWhitespace = (documentElement: HTMLElement) => {
  91. const walker = document.createTreeWalker(
  92. documentElement,
  93. NodeFilter.SHOW_TEXT
  94. )
  95. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  96. if (node.textContent === ' ') {
  97. node.textContent = ' '
  98. }
  99. }
  100. }
  101. const processMatchedElements = (documentElement: HTMLElement) => {
  102. for (const item of selectors) {
  103. for (const element of documentElement.querySelectorAll<any>(
  104. item.selector
  105. )) {
  106. if (!item.match || item.match(element)) {
  107. // start the markup
  108. if (item.start) {
  109. const start = document.createTextNode(item.start(element))
  110. if (item.inside) {
  111. element.prepend(start)
  112. } else {
  113. element.before(start)
  114. }
  115. }
  116. // end the markup
  117. if (item.end) {
  118. const end = document.createTextNode(item.end(element))
  119. if (item.inside) {
  120. element.append(end)
  121. } else {
  122. element.after(end)
  123. }
  124. }
  125. }
  126. }
  127. }
  128. }
  129. const matchingParents = (element: HTMLElement, selector: string) => {
  130. const matches = []
  131. for (
  132. let ancestor = element.parentElement?.closest(selector);
  133. ancestor;
  134. ancestor = ancestor.parentElement?.closest(selector)
  135. ) {
  136. matches.push(ancestor)
  137. }
  138. return matches
  139. }
  140. const processTables = (element: HTMLElement) => {
  141. for (const table of element.querySelectorAll('table')) {
  142. // create a wrapper element for the table and the caption
  143. const container = document.createElement('div')
  144. container.className = 'ol-table-wrap'
  145. table.after(container)
  146. // move the caption (if it exists) into the container before the table
  147. const caption = table.querySelector('caption')
  148. if (caption) {
  149. container.append(caption)
  150. }
  151. // move the table into the container
  152. container.append(table)
  153. }
  154. }
  155. const cellAlignment = new Map([
  156. ['left', 'l'],
  157. ['center', 'c'],
  158. ['right', 'r'],
  159. ])
  160. const tabular = (element: HTMLTableElement) => {
  161. const definitions: Array<{
  162. alignment: string
  163. borderLeft: boolean
  164. borderRight: boolean
  165. }> = []
  166. const rows = element.querySelectorAll('tr')
  167. for (const row of rows) {
  168. const cells = [...row.childNodes].filter(
  169. element => element.nodeName === 'TD' || element.nodeName === 'TH'
  170. ) as Array<HTMLTableCellElement>
  171. let index = 0
  172. for (const cell of cells) {
  173. // NOTE: reading the alignment and borders from the first cell definition in each column
  174. if (definitions[index] === undefined) {
  175. const { textAlign, borderLeftStyle, borderRightStyle } = cell.style
  176. definitions[index] = {
  177. alignment: textAlign,
  178. borderLeft: visibleBorderStyle(borderLeftStyle),
  179. borderRight: visibleBorderStyle(borderRightStyle),
  180. }
  181. }
  182. index += Number(cell.getAttribute('colspan') ?? 1)
  183. }
  184. }
  185. for (let index = 0; index <= definitions.length; index++) {
  186. // fill in missing definitions
  187. const item = definitions[index] || {
  188. alignment: 'left',
  189. borderLeft: false,
  190. borderRight: false,
  191. }
  192. // remove left border if previous column had a right border
  193. if (item.borderLeft && index > 0 && definitions[index - 1]?.borderRight) {
  194. item.borderLeft = false
  195. }
  196. }
  197. return definitions
  198. .flatMap(definition => [
  199. definition.borderLeft ? '|' : '',
  200. cellAlignment.get(definition.alignment) ?? 'l',
  201. definition.borderRight ? '|' : '',
  202. ])
  203. .filter(Boolean)
  204. .join(' ')
  205. }
  206. const listDepth = (
  207. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  208. ): number => Math.max(0, matchingParents(element, 'ul,ol').length - 1)
  209. const listIndent = (
  210. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  211. ): string => '\t'.repeat(listDepth(element))
  212. type ElementSelector<T extends string, E extends HTMLElement = HTMLElement> = {
  213. selector: T
  214. match?: (element: E) => boolean
  215. start?: (element: E) => string
  216. end?: (element: E) => string
  217. inside?: boolean
  218. }
  219. const createSelector = <
  220. T extends string,
  221. E extends HTMLElement = T extends keyof HTMLElementTagNameMap
  222. ? HTMLElementTagNameMap[T]
  223. : HTMLElement
  224. >({
  225. selector,
  226. ...elementSelector
  227. }: ElementSelector<T, E>) => ({
  228. selector,
  229. ...elementSelector,
  230. })
  231. const headings = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']
  232. const isHeading = (element: HTMLElement | null) => {
  233. return element && headings.includes(element.nodeName)
  234. }
  235. const hasContent = (element: HTMLElement): boolean => {
  236. return Boolean(element.textContent && element.textContent.trim().length > 0)
  237. }
  238. type BorderStyle =
  239. | 'borderTopStyle'
  240. | 'borderRightStyle'
  241. | 'borderBottomStyle'
  242. | 'borderLeftStyle'
  243. const visibleBorderStyle = (style: CSSStyleDeclaration[BorderStyle]): boolean =>
  244. !!style && style !== 'none' && style !== 'hidden'
  245. const rowHasBorderStyle = (
  246. element: HTMLTableRowElement,
  247. style: BorderStyle
  248. ): boolean => {
  249. if (visibleBorderStyle(element.style[style])) {
  250. return true
  251. }
  252. const cells = element.querySelectorAll<HTMLTableCellElement>('th,td')
  253. return [...cells].every(cell => visibleBorderStyle(cell.style[style]))
  254. }
  255. const isTableRowElement = (
  256. element: Element | null
  257. ): element is HTMLTableRowElement => element?.tagName === 'TR'
  258. const nextRowHasBorderStyle = (
  259. element: HTMLTableRowElement,
  260. style: BorderStyle
  261. ) => {
  262. const { nextElementSibling } = element
  263. return (
  264. isTableRowElement(nextElementSibling) &&
  265. rowHasBorderStyle(nextElementSibling, style)
  266. )
  267. }
  268. const startMulticolumn = (element: HTMLTableCellElement): string => {
  269. const colspan = element.getAttribute('colspan') ?? 1
  270. const alignment = cellAlignment.get(element.style.textAlign) ?? 'l'
  271. return `\\multicolumn{${Number(colspan)}}{${alignment}}{`
  272. }
  273. const selectors = [
  274. createSelector({
  275. selector: 'b',
  276. match: element =>
  277. element.style.fontWeight !== 'normal' &&
  278. !isHeading(element.parentElement) &&
  279. hasContent(element),
  280. start: () => '\\textbf{',
  281. end: () => '}',
  282. }),
  283. createSelector({
  284. selector: '*',
  285. match: element =>
  286. parseInt(element.style.fontWeight) > 400 && hasContent(element),
  287. start: () => '\\textbf{',
  288. end: () => '}',
  289. inside: true,
  290. }),
  291. createSelector({
  292. selector: 'strong',
  293. match: element => hasContent(element),
  294. start: () => '\\textbf{',
  295. end: () => '}',
  296. }),
  297. createSelector({
  298. selector: 'i',
  299. match: element =>
  300. element.style.fontStyle !== 'normal' && hasContent(element),
  301. start: () => '\\textit{',
  302. end: () => '}',
  303. }),
  304. createSelector({
  305. selector: '*',
  306. match: element =>
  307. element.style.fontStyle === 'italic' && hasContent(element),
  308. start: () => '\\textit{',
  309. end: () => '}',
  310. }),
  311. createSelector({
  312. selector: 'em',
  313. match: element => hasContent(element),
  314. start: () => '\\textit{',
  315. end: () => '}',
  316. }),
  317. createSelector({
  318. selector: 'sup',
  319. match: element => hasContent(element),
  320. start: () => '\\textsuperscript{',
  321. end: () => '}',
  322. }),
  323. createSelector({
  324. selector: 'span',
  325. match: element =>
  326. element.style.verticalAlign === 'super' && hasContent(element),
  327. start: () => '\\textsuperscript{',
  328. end: () => '}',
  329. }),
  330. createSelector({
  331. selector: 'sub',
  332. match: element => hasContent(element),
  333. start: () => '\\textsubscript{',
  334. end: () => '}',
  335. }),
  336. createSelector({
  337. selector: 'span',
  338. match: element =>
  339. element.style.verticalAlign === 'sub' && hasContent(element),
  340. start: () => '\\textsubscript{',
  341. end: () => '}',
  342. }),
  343. createSelector({
  344. selector: 'a',
  345. match: element => !!element.href && hasContent(element),
  346. start: (element: HTMLAnchorElement) => `\\href{${element.href}}{`,
  347. end: element => `}`,
  348. }),
  349. createSelector({
  350. selector: 'h1',
  351. match: element => !element.closest('table') && hasContent(element),
  352. start: () => `\n\n\\section{`,
  353. end: () => `}\n\n`,
  354. }),
  355. createSelector({
  356. selector: 'h2',
  357. match: element => !element.closest('table') && hasContent(element),
  358. start: () => `\n\n\\subsection{`,
  359. end: () => `}\n\n`,
  360. }),
  361. createSelector({
  362. selector: 'h3',
  363. match: element => !element.closest('table') && hasContent(element),
  364. start: () => `\n\n\\subsubsection{`,
  365. end: () => `}\n\n`,
  366. }),
  367. createSelector({
  368. selector: 'h4',
  369. match: element => !element.closest('table') && hasContent(element),
  370. start: () => `\n\n\\paragraph{`,
  371. end: () => `}\n\n`,
  372. }),
  373. createSelector({
  374. selector: 'h5',
  375. match: element => !element.closest('table') && hasContent(element),
  376. start: () => `\n\n\\subparagraph{`,
  377. end: () => `}\n\n`,
  378. }),
  379. // TODO: h6?
  380. createSelector({
  381. selector: 'br',
  382. match: element => element.parentElement?.nodeName !== 'TD', // TODO: why?
  383. start: () => `\n\n`,
  384. }),
  385. createSelector({
  386. selector: 'code',
  387. match: element =>
  388. element.parentElement?.nodeName !== 'PRE' && hasContent(element),
  389. start: () => `\\verb|`,
  390. end: () => `|`,
  391. }),
  392. createSelector({
  393. selector: 'pre > code',
  394. match: element => hasContent(element),
  395. start: () => `\n\n\\begin{verbatim}\n`,
  396. end: () => `\n\\end{verbatim}\n\n`,
  397. }),
  398. createSelector({
  399. selector: '.ol-table-wrap',
  400. start: () => `\n\n\\begin{table}\n\\centering\n`,
  401. end: () => `\n\\end{table}\n\n`,
  402. }),
  403. createSelector({
  404. selector: 'table',
  405. start: element => `\n\\begin{tabular}{${tabular(element)}}`,
  406. end: () => `\\end{tabular}\n`,
  407. }),
  408. createSelector({
  409. selector: 'thead',
  410. start: () => `\n`,
  411. end: () => `\n`,
  412. }),
  413. createSelector({
  414. selector: 'tfoot',
  415. start: () => `\n`,
  416. end: () => `\n`,
  417. }),
  418. createSelector({
  419. selector: 'tbody',
  420. start: () => `\n`,
  421. end: () => `\n`,
  422. }),
  423. createSelector({
  424. selector: 'tr',
  425. start: element => {
  426. const borderTop = rowHasBorderStyle(element, 'borderTopStyle')
  427. return borderTop ? '\\hline\n' : ''
  428. },
  429. end: element => {
  430. const borderBottom = rowHasBorderStyle(element, 'borderBottomStyle')
  431. return borderBottom && !nextRowHasBorderStyle(element, 'borderTopStyle')
  432. ? '\n\\hline\n'
  433. : '\n'
  434. },
  435. }),
  436. createSelector({
  437. selector: 'tr > td:not(:last-child), tr > th:not(:last-child)',
  438. start: (element: HTMLTableCellElement) => {
  439. const colspan = element.getAttribute('colspan')
  440. return colspan ? startMulticolumn(element) : ''
  441. },
  442. end: element => {
  443. const colspan = element.getAttribute('colspan')
  444. return colspan ? `} & ` : ` & `
  445. },
  446. }),
  447. createSelector({
  448. selector: 'tr > td:last-child, tr > th:last-child',
  449. start: (element: HTMLTableCellElement) => {
  450. const colspan = element.getAttribute('colspan')
  451. return colspan ? startMulticolumn(element) : ''
  452. },
  453. end: element => {
  454. const colspan = element.getAttribute('colspan')
  455. return colspan ? `} \\\\` : ` \\\\`
  456. },
  457. }),
  458. createSelector({
  459. selector: 'caption',
  460. start: () => `\n\n\\caption{`,
  461. end: () => `}\n\n`,
  462. }),
  463. createSelector({
  464. selector: 'ul',
  465. start: element => `\n\n${listIndent(element)}\\begin{itemize}`,
  466. end: element => `\n${listIndent(element)}\\end{itemize}\n`,
  467. }),
  468. createSelector({
  469. selector: 'ol',
  470. start: element => `\n\n${listIndent(element)}\\begin{enumerate}`,
  471. end: element => `\n${listIndent(element)}\\end{enumerate}\n`,
  472. }),
  473. createSelector({
  474. selector: 'li',
  475. start: element => `\n${listIndent(element)}\t\\item `,
  476. }),
  477. createSelector({
  478. selector: 'p',
  479. match: element =>
  480. element.nextElementSibling?.nodeName === 'P' && hasContent(element),
  481. end: () => '\n\n',
  482. }),
  483. createSelector({
  484. selector: 'blockquote',
  485. start: () => `\n\n\\begin{quote}\n`,
  486. end: () => `\n\\end{quote}\n\n`,
  487. }),
  488. ]