index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * @typedef {import('unist').Node} Node
  3. * @typedef {import('unist').Point} Point
  4. * @typedef {import('unist').Position} Position
  5. */
  6. /**
  7. * @typedef NodeLike
  8. * @property {string} type
  9. * @property {PositionLike | null | undefined} [position]
  10. *
  11. * @typedef PositionLike
  12. * @property {PointLike | null | undefined} [start]
  13. * @property {PointLike | null | undefined} [end]
  14. *
  15. * @typedef PointLike
  16. * @property {number | null | undefined} [line]
  17. * @property {number | null | undefined} [column]
  18. * @property {number | null | undefined} [offset]
  19. */
  20. /**
  21. * Get the ending point of `node`.
  22. *
  23. * @param node
  24. * Node.
  25. * @returns
  26. * Point.
  27. */
  28. export const pointEnd = point('end')
  29. /**
  30. * Get the starting point of `node`.
  31. *
  32. * @param node
  33. * Node.
  34. * @returns
  35. * Point.
  36. */
  37. export const pointStart = point('start')
  38. /**
  39. * Get the positional info of `node`.
  40. *
  41. * @param {'end' | 'start'} type
  42. * Side.
  43. * @returns
  44. * Getter.
  45. */
  46. function point(type) {
  47. return point
  48. /**
  49. * Get the point info of `node` at a bound side.
  50. *
  51. * @param {Node | NodeLike | null | undefined} [node]
  52. * @returns {Point | undefined}
  53. */
  54. function point(node) {
  55. const point = (node && node.position && node.position[type]) || {}
  56. if (
  57. typeof point.line === 'number' &&
  58. point.line > 0 &&
  59. typeof point.column === 'number' &&
  60. point.column > 0
  61. ) {
  62. return {
  63. line: point.line,
  64. column: point.column,
  65. offset:
  66. typeof point.offset === 'number' && point.offset > -1
  67. ? point.offset
  68. : undefined
  69. }
  70. }
  71. }
  72. }
  73. /**
  74. * Get the positional info of `node`.
  75. *
  76. * @param {Node | NodeLike | null | undefined} [node]
  77. * Node.
  78. * @returns {Position | undefined}
  79. * Position.
  80. */
  81. export function position(node) {
  82. const start = pointStart(node)
  83. const end = pointEnd(node)
  84. if (start && end) {
  85. return {start, end}
  86. }
  87. }