revert.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * @import {ElementContent} from 'hast'
  3. * @import {Reference, Nodes} from 'mdast'
  4. * @import {State} from './state.js'
  5. */
  6. /**
  7. * Return the content of a reference without definition as plain text.
  8. *
  9. * @param {State} state
  10. * Info passed around.
  11. * @param {Extract<Nodes, Reference>} node
  12. * Reference node (image, link).
  13. * @returns {Array<ElementContent>}
  14. * hast content.
  15. */
  16. export function revert(state, node) {
  17. const subtype = node.referenceType
  18. let suffix = ']'
  19. if (subtype === 'collapsed') {
  20. suffix += '[]'
  21. } else if (subtype === 'full') {
  22. suffix += '[' + (node.label || node.identifier) + ']'
  23. }
  24. if (node.type === 'imageReference') {
  25. return [{type: 'text', value: '![' + node.alt + suffix}]
  26. }
  27. const contents = state.all(node)
  28. const head = contents[0]
  29. if (head && head.type === 'text') {
  30. head.value = '[' + head.value
  31. } else {
  32. contents.unshift({type: 'text', value: '['})
  33. }
  34. const tail = contents[contents.length - 1]
  35. if (tail && tail.type === 'text') {
  36. tail.value += suffix
  37. } else {
  38. contents.push({type: 'text', value: suffix})
  39. }
  40. return contents
  41. }