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