index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /**
  2. * @typedef {import('unist').Node} UnistNode
  3. * @typedef {import('unist').Parent} UnistParent
  4. */
  5. /**
  6. * @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test
  7. * Test from `unist-util-is`.
  8. *
  9. * Note: we have remove and add `undefined`, because otherwise when generating
  10. * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,
  11. * which doesn’t work when publishing on npm.
  12. */
  13. /**
  14. * @typedef {(
  15. * Fn extends (value: any) => value is infer Thing
  16. * ? Thing
  17. * : Fallback
  18. * )} Predicate
  19. * Get the value of a type guard `Fn`.
  20. * @template Fn
  21. * Value; typically function that is a type guard (such as `(x): x is Y`).
  22. * @template Fallback
  23. * Value to yield if `Fn` is not a type guard.
  24. */
  25. /**
  26. * @typedef {(
  27. * Check extends null | undefined // No test.
  28. * ? Value
  29. * : Value extends {type: Check} // String (type) test.
  30. * ? Value
  31. * : Value extends Check // Partial test.
  32. * ? Value
  33. * : Check extends Function // Function test.
  34. * ? Predicate<Check, Value> extends Value
  35. * ? Predicate<Check, Value>
  36. * : never
  37. * : never // Some other test?
  38. * )} MatchesOne
  39. * Check whether a node matches a primitive check in the type system.
  40. * @template Value
  41. * Value; typically unist `Node`.
  42. * @template Check
  43. * Value; typically `unist-util-is`-compatible test, but not arrays.
  44. */
  45. /**
  46. * @typedef {(
  47. * Check extends Array<any>
  48. * ? MatchesOne<Value, Check[keyof Check]>
  49. * : MatchesOne<Value, Check>
  50. * )} Matches
  51. * Check whether a node matches a check in the type system.
  52. * @template Value
  53. * Value; typically unist `Node`.
  54. * @template Check
  55. * Value; typically `unist-util-is`-compatible test.
  56. */
  57. /**
  58. * @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint
  59. * Number; capped reasonably.
  60. */
  61. /**
  62. * @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment
  63. * Increment a number in the type system.
  64. * @template {Uint} [I=0]
  65. * Index.
  66. */
  67. /**
  68. * @typedef {(
  69. * Node extends UnistParent
  70. * ? Node extends {children: Array<infer Children>}
  71. * ? Child extends Children ? Node : never
  72. * : never
  73. * : never
  74. * )} InternalParent
  75. * Collect nodes that can be parents of `Child`.
  76. * @template {UnistNode} Node
  77. * All node types in a tree.
  78. * @template {UnistNode} Child
  79. * Node to search for.
  80. */
  81. /**
  82. * @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent
  83. * Collect nodes in `Tree` that can be parents of `Child`.
  84. * @template {UnistNode} Tree
  85. * All node types in a tree.
  86. * @template {UnistNode} Child
  87. * Node to search for.
  88. */
  89. /**
  90. * @typedef {(
  91. * Depth extends Max
  92. * ? never
  93. * :
  94. * | InternalParent<Node, Child>
  95. * | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>
  96. * )} InternalAncestor
  97. * Collect nodes in `Tree` that can be ancestors of `Child`.
  98. * @template {UnistNode} Node
  99. * All node types in a tree.
  100. * @template {UnistNode} Child
  101. * Node to search for.
  102. * @template {Uint} [Max=10]
  103. * Max; searches up to this depth.
  104. * @template {Uint} [Depth=0]
  105. * Current depth.
  106. */
  107. /**
  108. * @typedef {InternalAncestor<InclusiveDescendant<Tree>, Child>} Ancestor
  109. * Collect nodes in `Tree` that can be ancestors of `Child`.
  110. * @template {UnistNode} Tree
  111. * All node types in a tree.
  112. * @template {UnistNode} Child
  113. * Node to search for.
  114. */
  115. /**
  116. * @typedef {(
  117. * Tree extends UnistParent
  118. * ? Depth extends Max
  119. * ? Tree
  120. * : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>
  121. * : Tree
  122. * )} InclusiveDescendant
  123. * Collect all (inclusive) descendants of `Tree`.
  124. *
  125. * > 👉 **Note**: for performance reasons, this seems to be the fastest way to
  126. * > recurse without actually running into an infinite loop, which the
  127. * > previous version did.
  128. * >
  129. * > Practically, a max of `2` is typically enough assuming a `Root` is
  130. * > passed, but it doesn’t improve performance.
  131. * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.
  132. * > Using up to `10` doesn’t hurt or help either.
  133. * @template {UnistNode} Tree
  134. * Tree type.
  135. * @template {Uint} [Max=10]
  136. * Max; searches up to this depth.
  137. * @template {Uint} [Depth=0]
  138. * Current depth.
  139. */
  140. /**
  141. * @typedef {'skip' | boolean} Action
  142. * Union of the action types.
  143. *
  144. * @typedef {number} Index
  145. * Move to the sibling at `index` next (after node itself is completely
  146. * traversed).
  147. *
  148. * Useful if mutating the tree, such as removing the node the visitor is
  149. * currently on, or any of its previous siblings.
  150. * Results less than 0 or greater than or equal to `children.length` stop
  151. * traversing the parent.
  152. *
  153. * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple
  154. * List with one or two values, the first an action, the second an index.
  155. *
  156. * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult
  157. * Any value that can be returned from a visitor.
  158. */
  159. /**
  160. * @callback Visitor
  161. * Handle a node (matching `test`, if given).
  162. *
  163. * Visitors are free to transform `node`.
  164. * They can also transform the parent of node (the last of `ancestors`).
  165. *
  166. * Replacing `node` itself, if `SKIP` is not returned, still causes its
  167. * descendants to be walked (which is a bug).
  168. *
  169. * When adding or removing previous siblings of `node` (or next siblings, in
  170. * case of reverse), the `Visitor` should return a new `Index` to specify the
  171. * sibling to traverse after `node` is traversed.
  172. * Adding or removing next siblings of `node` (or previous siblings, in case
  173. * of reverse) is handled as expected without needing to return a new `Index`.
  174. *
  175. * Removing the children property of an ancestor still results in them being
  176. * traversed.
  177. * @param {Visited} node
  178. * Found node.
  179. * @param {Array<VisitedParents>} ancestors
  180. * Ancestors of `node`.
  181. * @returns {VisitorResult}
  182. * What to do next.
  183. *
  184. * An `Index` is treated as a tuple of `[CONTINUE, Index]`.
  185. * An `Action` is treated as a tuple of `[Action]`.
  186. *
  187. * Passing a tuple back only makes sense if the `Action` is `SKIP`.
  188. * When the `Action` is `EXIT`, that action can be returned.
  189. * When the `Action` is `CONTINUE`, `Index` can be returned.
  190. * @template {UnistNode} [Visited=UnistNode]
  191. * Visited node type.
  192. * @template {UnistParent} [VisitedParents=UnistParent]
  193. * Ancestor type.
  194. */
  195. /**
  196. * @typedef {Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>} BuildVisitor
  197. * Build a typed `Visitor` function from a tree and a test.
  198. *
  199. * It will infer which values are passed as `node` and which as `parents`.
  200. * @template {UnistNode} [Tree=UnistNode]
  201. * Tree type.
  202. * @template {Test} [Check=Test]
  203. * Test type.
  204. */
  205. import {convert} from 'unist-util-is'
  206. import {color} from 'unist-util-visit-parents/do-not-use-color'
  207. /** @type {Readonly<ActionTuple>} */
  208. const empty = []
  209. /**
  210. * Continue traversing as normal.
  211. */
  212. export const CONTINUE = true
  213. /**
  214. * Stop traversing immediately.
  215. */
  216. export const EXIT = false
  217. /**
  218. * Do not traverse this node’s children.
  219. */
  220. export const SKIP = 'skip'
  221. /**
  222. * Visit nodes, with ancestral information.
  223. *
  224. * This algorithm performs *depth-first* *tree traversal* in *preorder*
  225. * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).
  226. *
  227. * You can choose for which nodes `visitor` is called by passing a `test`.
  228. * For complex tests, you should test yourself in `visitor`, as it will be
  229. * faster and will have improved type information.
  230. *
  231. * Walking the tree is an intensive task.
  232. * Make use of the return values of the visitor when possible.
  233. * Instead of walking a tree multiple times, walk it once, use `unist-util-is`
  234. * to check if a node matches, and then perform different operations.
  235. *
  236. * You can change the tree.
  237. * See `Visitor` for more info.
  238. *
  239. * @overload
  240. * @param {Tree} tree
  241. * @param {Check} check
  242. * @param {BuildVisitor<Tree, Check>} visitor
  243. * @param {boolean | null | undefined} [reverse]
  244. * @returns {undefined}
  245. *
  246. * @overload
  247. * @param {Tree} tree
  248. * @param {BuildVisitor<Tree>} visitor
  249. * @param {boolean | null | undefined} [reverse]
  250. * @returns {undefined}
  251. *
  252. * @param {UnistNode} tree
  253. * Tree to traverse.
  254. * @param {Visitor | Test} test
  255. * `unist-util-is`-compatible test
  256. * @param {Visitor | boolean | null | undefined} [visitor]
  257. * Handle each node.
  258. * @param {boolean | null | undefined} [reverse]
  259. * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).
  260. * @returns {undefined}
  261. * Nothing.
  262. *
  263. * @template {UnistNode} Tree
  264. * Node type.
  265. * @template {Test} Check
  266. * `unist-util-is`-compatible test.
  267. */
  268. export function visitParents(tree, test, visitor, reverse) {
  269. /** @type {Test} */
  270. let check
  271. if (typeof test === 'function' && typeof visitor !== 'function') {
  272. reverse = visitor
  273. // @ts-expect-error no visitor given, so `visitor` is test.
  274. visitor = test
  275. } else {
  276. // @ts-expect-error visitor given, so `test` isn’t a visitor.
  277. check = test
  278. }
  279. const is = convert(check)
  280. const step = reverse ? -1 : 1
  281. factory(tree, undefined, [])()
  282. /**
  283. * @param {UnistNode} node
  284. * @param {number | undefined} index
  285. * @param {Array<UnistParent>} parents
  286. */
  287. function factory(node, index, parents) {
  288. const value = /** @type {Record<string, unknown>} */ (
  289. node && typeof node === 'object' ? node : {}
  290. )
  291. if (typeof value.type === 'string') {
  292. const name =
  293. // `hast`
  294. typeof value.tagName === 'string'
  295. ? value.tagName
  296. : // `xast`
  297. typeof value.name === 'string'
  298. ? value.name
  299. : undefined
  300. Object.defineProperty(visit, 'name', {
  301. value:
  302. 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'
  303. })
  304. }
  305. return visit
  306. function visit() {
  307. /** @type {Readonly<ActionTuple>} */
  308. let result = empty
  309. /** @type {Readonly<ActionTuple>} */
  310. let subresult
  311. /** @type {number} */
  312. let offset
  313. /** @type {Array<UnistParent>} */
  314. let grandparents
  315. if (!test || is(node, index, parents[parents.length - 1] || undefined)) {
  316. // @ts-expect-error: `visitor` is now a visitor.
  317. result = toResult(visitor(node, parents))
  318. if (result[0] === EXIT) {
  319. return result
  320. }
  321. }
  322. if ('children' in node && node.children) {
  323. const nodeAsParent = /** @type {UnistParent} */ (node)
  324. if (nodeAsParent.children && result[0] !== SKIP) {
  325. offset = (reverse ? nodeAsParent.children.length : -1) + step
  326. grandparents = parents.concat(nodeAsParent)
  327. while (offset > -1 && offset < nodeAsParent.children.length) {
  328. const child = nodeAsParent.children[offset]
  329. subresult = factory(child, offset, grandparents)()
  330. if (subresult[0] === EXIT) {
  331. return subresult
  332. }
  333. offset =
  334. typeof subresult[1] === 'number' ? subresult[1] : offset + step
  335. }
  336. }
  337. }
  338. return result
  339. }
  340. }
  341. }
  342. /**
  343. * Turn a return value into a clean result.
  344. *
  345. * @param {VisitorResult} value
  346. * Valid return values from visitors.
  347. * @returns {Readonly<ActionTuple>}
  348. * Clean result.
  349. */
  350. function toResult(value) {
  351. if (Array.isArray(value)) {
  352. return value
  353. }
  354. if (typeof value === 'number') {
  355. return [CONTINUE, value]
  356. }
  357. return value === null || value === undefined ? empty : [value]
  358. }