index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. 'use strict'
  2. module.exports = toHast
  3. var xtend = require('xtend')
  4. var u = require('unist-builder')
  5. var visit = require('unist-util-visit')
  6. var position = require('unist-util-position')
  7. var generated = require('unist-util-generated')
  8. var definitions = require('mdast-util-definitions')
  9. var one = require('./one')
  10. var footer = require('./footer')
  11. var handlers = require('./handlers')
  12. // Factory to transform.
  13. function factory(tree, options) {
  14. var settings = options || {}
  15. var dangerous = settings.allowDangerousHTML
  16. h.dangerous = dangerous
  17. h.definition = definitions(tree, settings)
  18. h.footnotes = []
  19. h.augment = augment
  20. h.handlers = xtend(handlers, settings.handlers || {})
  21. visit(tree, 'footnoteDefinition', visitor)
  22. return h
  23. // Finalise the created `right`, a hast node, from `left`, an mdast node.
  24. function augment(left, right) {
  25. var data
  26. var ctx
  27. // Handle `data.hName`, `data.hProperties, `hChildren`.
  28. if (left && 'data' in left) {
  29. data = left.data
  30. if (right.type === 'element' && data.hName) {
  31. right.tagName = data.hName
  32. }
  33. if (right.type === 'element' && data.hProperties) {
  34. right.properties = xtend(right.properties, data.hProperties)
  35. }
  36. if (right.children && data.hChildren) {
  37. right.children = data.hChildren
  38. }
  39. }
  40. ctx = left && left.position ? left : {position: left}
  41. if (!generated(ctx)) {
  42. right.position = {
  43. start: position.start(ctx),
  44. end: position.end(ctx)
  45. }
  46. }
  47. return right
  48. }
  49. // Create an element for a `node`.
  50. function h(node, tagName, props, children) {
  51. if (
  52. (children === undefined || children === null) &&
  53. typeof props === 'object' &&
  54. 'length' in props
  55. ) {
  56. children = props
  57. props = {}
  58. }
  59. return augment(node, {
  60. type: 'element',
  61. tagName: tagName,
  62. properties: props || {},
  63. children: children || []
  64. })
  65. }
  66. function visitor(definition) {
  67. h.footnotes.push(definition)
  68. }
  69. }
  70. // Transform `tree`, which is an mdast node, to a hast node.
  71. function toHast(tree, options) {
  72. var h = factory(tree, options)
  73. var node = one(h, tree)
  74. var footnotes = footer(h)
  75. if (node && node.children && footnotes) {
  76. node.children = node.children.concat(u('text', '\n'), footnotes)
  77. }
  78. return node
  79. }