index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @fileoverview latex 插件
  3. * katex.min.js来源 https://github.com/rojer95/katex-mini
  4. */
  5. const parse = require('./katex.min')
  6. function Latex () {
  7. }
  8. Latex.prototype.onParse = function (node, vm) {
  9. // $...$包裹的内容为latex公式
  10. if (!vm.options.editable && node.type === 'text' && node.text.includes('$')) {
  11. const part = node.text.split(/(\${1,2})/)
  12. const children = []
  13. let status = 0
  14. for (let i = 0; i < part.length; i++) {
  15. if (i % 2 === 0) {
  16. // 文本内容
  17. if (part[i]) {
  18. if (status === 0) {
  19. children.push({
  20. type: 'text',
  21. text: part[i]
  22. })
  23. } else {
  24. if (status === 1) {
  25. // 行内公式
  26. const nodes = parse.default(part[i])
  27. children.push({
  28. name: 'span',
  29. attrs: {},
  30. l: 'T',
  31. f: 'display:inline-block',
  32. children: nodes
  33. })
  34. } else {
  35. // 块公式
  36. const nodes = parse.default(part[i], {
  37. displayMode: true
  38. })
  39. children.push({
  40. name: 'div',
  41. attrs: {
  42. style: 'text-align:center'
  43. },
  44. children: nodes
  45. })
  46. }
  47. }
  48. }
  49. } else {
  50. // 分隔符
  51. if (part[i] === '$' && part[i + 2] === '$') {
  52. // 行内公式
  53. status = 1
  54. part[i + 2] = ''
  55. } else if (part[i] === '$$' && part[i + 2] === '$$') {
  56. // 块公式
  57. status = 2
  58. part[i + 2] = ''
  59. } else {
  60. if (part[i] && part[i] !== '$$') {
  61. // 普通$符号
  62. part[i + 1] = part[i] + part[i + 1]
  63. }
  64. // 重置状态
  65. status = 0
  66. }
  67. }
  68. }
  69. delete node.type
  70. delete node.text
  71. node.name = 'span'
  72. node.attrs = {}
  73. node.children = children
  74. }
  75. }
  76. module.exports = Latex