track.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * @import {CreateTracker, TrackCurrent, TrackMove, TrackShift} from '../types.js'
  3. */
  4. /**
  5. * Track positional info in the output.
  6. *
  7. * @type {CreateTracker}
  8. */
  9. export function track(config) {
  10. // Defaults are used to prevent crashes when older utilities somehow activate
  11. // this code.
  12. /* c8 ignore next 5 */
  13. const options = config || {}
  14. const now = options.now || {}
  15. let lineShift = options.lineShift || 0
  16. let line = now.line || 1
  17. let column = now.column || 1
  18. return {move, current, shift}
  19. /**
  20. * Get the current tracked info.
  21. *
  22. * @type {TrackCurrent}
  23. */
  24. function current() {
  25. return {now: {line, column}, lineShift}
  26. }
  27. /**
  28. * Define an increased line shift (the typical indent for lines).
  29. *
  30. * @type {TrackShift}
  31. */
  32. function shift(value) {
  33. lineShift += value
  34. }
  35. /**
  36. * Move past some generated markdown.
  37. *
  38. * @type {TrackMove}
  39. */
  40. function move(input) {
  41. // eslint-disable-next-line unicorn/prefer-default-parameters
  42. const value = input || ''
  43. const chunks = value.split(/\r?\n|\r/g)
  44. const tail = chunks[chunks.length - 1]
  45. line += chunks.length - 1
  46. column =
  47. chunks.length === 1 ? column + tail.length : 1 + tail.length + lineShift
  48. return value
  49. }
  50. }