paste-html.ts 15 KB

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