link-reference.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * @typedef {import('mdast').LinkReference} LinkReference
  3. * @typedef {import('mdast').Parents} Parents
  4. * @typedef {import('../types.js').Info} Info
  5. * @typedef {import('../types.js').State} State
  6. */
  7. linkReference.peek = linkReferencePeek
  8. /**
  9. * @param {LinkReference} node
  10. * @param {Parents | undefined} _
  11. * @param {State} state
  12. * @param {Info} info
  13. * @returns {string}
  14. */
  15. export function linkReference(node, _, state, info) {
  16. const type = node.referenceType
  17. const exit = state.enter('linkReference')
  18. let subexit = state.enter('label')
  19. const tracker = state.createTracker(info)
  20. let value = tracker.move('[')
  21. const text = state.containerPhrasing(node, {
  22. before: value,
  23. after: ']',
  24. ...tracker.current()
  25. })
  26. value += tracker.move(text + '][')
  27. subexit()
  28. // Hide the fact that we’re in phrasing, because escapes don’t work.
  29. const stack = state.stack
  30. state.stack = []
  31. subexit = state.enter('reference')
  32. // Note: for proper tracking, we should reset the output positions when we end
  33. // up making a `shortcut` reference, because then there is no brace output.
  34. // Practically, in that case, there is no content, so it doesn’t matter that
  35. // we’ve tracked one too many characters.
  36. const reference = state.safe(state.associationId(node), {
  37. before: value,
  38. after: ']',
  39. ...tracker.current()
  40. })
  41. subexit()
  42. state.stack = stack
  43. exit()
  44. if (type === 'full' || !text || text !== reference) {
  45. value += tracker.move(reference + ']')
  46. } else if (type === 'shortcut') {
  47. // Remove the unwanted `[`.
  48. value = value.slice(0, -1)
  49. } else {
  50. value += tracker.move(']')
  51. }
  52. return value
  53. }
  54. /**
  55. * @returns {string}
  56. */
  57. function linkReferencePeek() {
  58. return '['
  59. }