Refactor routing in App component to enhance navigation and improve error handling by integrating dynamic routes and updating the NotFound route.

This commit is contained in:
becarta
2025-05-23 12:43:00 +02:00
parent f40db0f5c9
commit a544759a3b
11127 changed files with 1647032 additions and 0 deletions

14
node_modules/unist-util-visit-parents/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
export type {Test} from 'unist-util-is'
export type {
Action,
ActionTuple,
BuildVisitor,
// Undocumented: used in `unist-util-visit`:
InclusiveDescendant,
Index,
// Undocumented: used in `unist-util-visit`:
Matches,
Visitor,
VisitorResult
} from './lib/index.js'
export {CONTINUE, EXIT, SKIP, visitParents} from './lib/index.js'

2
node_modules/unist-util-visit-parents/index.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
// Note: types exported from `index.d.ts`
export {CONTINUE, EXIT, SKIP, visitParents} from './lib/index.js'

5
node_modules/unist-util-visit-parents/lib/color.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
/**
* @param {string} d
* @returns {string}
*/
export function color(d: string): string

7
node_modules/unist-util-visit-parents/lib/color.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
/**
* @param {string} d
* @returns {string}
*/
export function color(d) {
return d
}

View File

@@ -0,0 +1,5 @@
/**
* @param {string} d
* @returns {string}
*/
export function color(d: string): string

View File

@@ -0,0 +1,7 @@
/**
* @param {string} d
* @returns {string}
*/
export function color(d) {
return '\u001B[33m' + d + '\u001B[39m'
}

230
node_modules/unist-util-visit-parents/lib/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,230 @@
export function visitParents<
Tree extends import('unist').Node,
Check extends Test
>(
tree: Tree,
check: Check,
visitor: BuildVisitor<Tree, Check>,
reverse?: boolean | null | undefined
): undefined
export function visitParents<
Tree extends import('unist').Node,
Check extends Test
>(
tree: Tree,
visitor: BuildVisitor<Tree, Test>,
reverse?: boolean | null | undefined
): undefined
/**
* Continue traversing as normal.
*/
export const CONTINUE: true
/**
* Stop traversing immediately.
*/
export const EXIT: false
/**
* Do not traverse this nodes children.
*/
export const SKIP: 'skip'
export type UnistNode = import('unist').Node
export type UnistParent = import('unist').Parent
/**
* Test from `unist-util-is`.
*
* Note: we have remove and add `undefined`, because otherwise when generating
* automatic `.d.ts` files, TS tries to flatten paths from a local perspective,
* which doesnt work when publishing on npm.
*/
export type Test = Exclude<import('unist-util-is').Test, undefined> | undefined
/**
* Get the value of a type guard `Fn`.
*/
export type Predicate<Fn, Fallback> = Fn extends (
value: any
) => value is infer Thing
? Thing
: Fallback
/**
* Check whether a node matches a primitive check in the type system.
*/
export type MatchesOne<Value, Check> = Check extends null | undefined
? Value
: Value extends {
type: Check
}
? Value
: Value extends Check
? Value
: Check extends Function
? Predicate<Check, Value> extends Value
? Predicate<Check, Value>
: never
: never
/**
* Check whether a node matches a check in the type system.
*/
export type Matches<Value, Check> = Check extends Array<any>
? MatchesOne<Value, Check[keyof Check]>
: MatchesOne<Value, Check>
/**
* Number; capped reasonably.
*/
export type Uint = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
/**
* Increment a number in the type system.
*/
export type Increment<I extends Uint = 0> = 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
/**
* Collect nodes that can be parents of `Child`.
*/
export type InternalParent<
Node extends import('unist').Node,
Child extends import('unist').Node
> = Node extends import('unist').Parent
? Node extends {
children: (infer Children)[]
}
? Child extends Children
? Node
: never
: never
: never
/**
* Collect nodes in `Tree` that can be parents of `Child`.
*/
export type Parent<
Tree extends import('unist').Node,
Child extends import('unist').Node
> = InternalParent<InclusiveDescendant<Tree>, Child>
/**
* Collect nodes in `Tree` that can be ancestors of `Child`.
*/
export type InternalAncestor<
Node extends import('unist').Node,
Child extends import('unist').Node,
Max extends Uint = 10,
Depth extends Uint = 0
> = Depth extends Max
? never
:
| InternalParent<Node, Child>
| InternalAncestor<
Node,
InternalParent<Node, Child>,
Max,
Increment<Depth>
>
/**
* Collect nodes in `Tree` that can be ancestors of `Child`.
*/
export type Ancestor<
Tree extends import('unist').Node,
Child extends import('unist').Node
> = InternalAncestor<InclusiveDescendant<Tree>, Child>
/**
* Collect all (inclusive) descendants of `Tree`.
*
* > 👉 **Note**: for performance reasons, this seems to be the fastest way to
* > recurse without actually running into an infinite loop, which the
* > previous version did.
* >
* > Practically, a max of `2` is typically enough assuming a `Root` is
* > passed, but it doesnt improve performance.
* > It gets higher with `List > ListItem > Table > TableRow > TableCell`.
* > Using up to `10` doesnt hurt or help either.
*/
export type InclusiveDescendant<
Tree extends import('unist').Node,
Max extends Uint = 10,
Depth extends Uint = 0
> = Tree extends UnistParent
? Depth extends Max
? Tree
:
| Tree
| InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>
: Tree
/**
* Union of the action types.
*/
export type Action = 'skip' | boolean
/**
* Move to the sibling at `index` next (after node itself is completely
* traversed).
*
* Useful if mutating the tree, such as removing the node the visitor is
* currently on, or any of its previous siblings.
* Results less than 0 or greater than or equal to `children.length` stop
* traversing the parent.
*/
export type Index = number
/**
* List with one or two values, the first an action, the second an index.
*/
export type ActionTuple = [
(Action | null | undefined | void)?,
(Index | null | undefined)?
]
/**
* Any value that can be returned from a visitor.
*/
export type VisitorResult =
| Action
| [(void | Action | null | undefined)?, (number | null | undefined)?]
| Index
| null
| undefined
| void
/**
* Handle a node (matching `test`, if given).
*
* Visitors are free to transform `node`.
* They can also transform the parent of node (the last of `ancestors`).
*
* Replacing `node` itself, if `SKIP` is not returned, still causes its
* descendants to be walked (which is a bug).
*
* When adding or removing previous siblings of `node` (or next siblings, in
* case of reverse), the `Visitor` should return a new `Index` to specify the
* sibling to traverse after `node` is traversed.
* Adding or removing next siblings of `node` (or previous siblings, in case
* of reverse) is handled as expected without needing to return a new `Index`.
*
* Removing the children property of an ancestor still results in them being
* traversed.
*/
export type Visitor<
Visited extends import('unist').Node = import('unist').Node,
VisitedParents extends import('unist').Parent = import('unist').Parent
> = (node: Visited, ancestors: Array<VisitedParents>) => VisitorResult
/**
* Build a typed `Visitor` function from a tree and a test.
*
* It will infer which values are passed as `node` and which as `parents`.
*/
export type BuildVisitor<
Tree extends import('unist').Node = import('unist').Node,
Check extends Test = Test
> = Visitor<
Matches<InclusiveDescendant<Tree>, Check>,
Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>
>

398
node_modules/unist-util-visit-parents/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,398 @@
/**
* @typedef {import('unist').Node} UnistNode
* @typedef {import('unist').Parent} UnistParent
*/
/**
* @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test
* Test from `unist-util-is`.
*
* Note: we have remove and add `undefined`, because otherwise when generating
* automatic `.d.ts` files, TS tries to flatten paths from a local perspective,
* which doesnt work when publishing on npm.
*/
/**
* @typedef {(
* Fn extends (value: any) => value is infer Thing
* ? Thing
* : Fallback
* )} Predicate
* Get the value of a type guard `Fn`.
* @template Fn
* Value; typically function that is a type guard (such as `(x): x is Y`).
* @template Fallback
* Value to yield if `Fn` is not a type guard.
*/
/**
* @typedef {(
* Check extends null | undefined // No test.
* ? Value
* : Value extends {type: Check} // String (type) test.
* ? Value
* : Value extends Check // Partial test.
* ? Value
* : Check extends Function // Function test.
* ? Predicate<Check, Value> extends Value
* ? Predicate<Check, Value>
* : never
* : never // Some other test?
* )} MatchesOne
* Check whether a node matches a primitive check in the type system.
* @template Value
* Value; typically unist `Node`.
* @template Check
* Value; typically `unist-util-is`-compatible test, but not arrays.
*/
/**
* @typedef {(
* Check extends Array<any>
* ? MatchesOne<Value, Check[keyof Check]>
* : MatchesOne<Value, Check>
* )} Matches
* Check whether a node matches a check in the type system.
* @template Value
* Value; typically unist `Node`.
* @template Check
* Value; typically `unist-util-is`-compatible test.
*/
/**
* @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint
* Number; capped reasonably.
*/
/**
* @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
* Increment a number in the type system.
* @template {Uint} [I=0]
* Index.
*/
/**
* @typedef {(
* Node extends UnistParent
* ? Node extends {children: Array<infer Children>}
* ? Child extends Children ? Node : never
* : never
* : never
* )} InternalParent
* Collect nodes that can be parents of `Child`.
* @template {UnistNode} Node
* All node types in a tree.
* @template {UnistNode} Child
* Node to search for.
*/
/**
* @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent
* Collect nodes in `Tree` that can be parents of `Child`.
* @template {UnistNode} Tree
* All node types in a tree.
* @template {UnistNode} Child
* Node to search for.
*/
/**
* @typedef {(
* Depth extends Max
* ? never
* :
* | InternalParent<Node, Child>
* | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>
* )} InternalAncestor
* Collect nodes in `Tree` that can be ancestors of `Child`.
* @template {UnistNode} Node
* All node types in a tree.
* @template {UnistNode} Child
* Node to search for.
* @template {Uint} [Max=10]
* Max; searches up to this depth.
* @template {Uint} [Depth=0]
* Current depth.
*/
/**
* @typedef {InternalAncestor<InclusiveDescendant<Tree>, Child>} Ancestor
* Collect nodes in `Tree` that can be ancestors of `Child`.
* @template {UnistNode} Tree
* All node types in a tree.
* @template {UnistNode} Child
* Node to search for.
*/
/**
* @typedef {(
* Tree extends UnistParent
* ? Depth extends Max
* ? Tree
* : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>
* : Tree
* )} InclusiveDescendant
* Collect all (inclusive) descendants of `Tree`.
*
* > 👉 **Note**: for performance reasons, this seems to be the fastest way to
* > recurse without actually running into an infinite loop, which the
* > previous version did.
* >
* > Practically, a max of `2` is typically enough assuming a `Root` is
* > passed, but it doesnt improve performance.
* > It gets higher with `List > ListItem > Table > TableRow > TableCell`.
* > Using up to `10` doesnt hurt or help either.
* @template {UnistNode} Tree
* Tree type.
* @template {Uint} [Max=10]
* Max; searches up to this depth.
* @template {Uint} [Depth=0]
* Current depth.
*/
/**
* @typedef {'skip' | boolean} Action
* Union of the action types.
*
* @typedef {number} Index
* Move to the sibling at `index` next (after node itself is completely
* traversed).
*
* Useful if mutating the tree, such as removing the node the visitor is
* currently on, or any of its previous siblings.
* Results less than 0 or greater than or equal to `children.length` stop
* traversing the parent.
*
* @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple
* List with one or two values, the first an action, the second an index.
*
* @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult
* Any value that can be returned from a visitor.
*/
/**
* @callback Visitor
* Handle a node (matching `test`, if given).
*
* Visitors are free to transform `node`.
* They can also transform the parent of node (the last of `ancestors`).
*
* Replacing `node` itself, if `SKIP` is not returned, still causes its
* descendants to be walked (which is a bug).
*
* When adding or removing previous siblings of `node` (or next siblings, in
* case of reverse), the `Visitor` should return a new `Index` to specify the
* sibling to traverse after `node` is traversed.
* Adding or removing next siblings of `node` (or previous siblings, in case
* of reverse) is handled as expected without needing to return a new `Index`.
*
* Removing the children property of an ancestor still results in them being
* traversed.
* @param {Visited} node
* Found node.
* @param {Array<VisitedParents>} ancestors
* Ancestors of `node`.
* @returns {VisitorResult}
* What to do next.
*
* An `Index` is treated as a tuple of `[CONTINUE, Index]`.
* An `Action` is treated as a tuple of `[Action]`.
*
* Passing a tuple back only makes sense if the `Action` is `SKIP`.
* When the `Action` is `EXIT`, that action can be returned.
* When the `Action` is `CONTINUE`, `Index` can be returned.
* @template {UnistNode} [Visited=UnistNode]
* Visited node type.
* @template {UnistParent} [VisitedParents=UnistParent]
* Ancestor type.
*/
/**
* @typedef {Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>} BuildVisitor
* Build a typed `Visitor` function from a tree and a test.
*
* It will infer which values are passed as `node` and which as `parents`.
* @template {UnistNode} [Tree=UnistNode]
* Tree type.
* @template {Test} [Check=Test]
* Test type.
*/
import {convert} from 'unist-util-is'
import {color} from 'unist-util-visit-parents/do-not-use-color'
/** @type {Readonly<ActionTuple>} */
const empty = []
/**
* Continue traversing as normal.
*/
export const CONTINUE = true
/**
* Stop traversing immediately.
*/
export const EXIT = false
/**
* Do not traverse this nodes children.
*/
export const SKIP = 'skip'
/**
* Visit nodes, with ancestral information.
*
* This algorithm performs *depth-first* *tree traversal* in *preorder*
* (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).
*
* You can choose for which nodes `visitor` is called by passing a `test`.
* For complex tests, you should test yourself in `visitor`, as it will be
* faster and will have improved type information.
*
* Walking the tree is an intensive task.
* Make use of the return values of the visitor when possible.
* Instead of walking a tree multiple times, walk it once, use `unist-util-is`
* to check if a node matches, and then perform different operations.
*
* You can change the tree.
* See `Visitor` for more info.
*
* @overload
* @param {Tree} tree
* @param {Check} check
* @param {BuildVisitor<Tree, Check>} visitor
* @param {boolean | null | undefined} [reverse]
* @returns {undefined}
*
* @overload
* @param {Tree} tree
* @param {BuildVisitor<Tree>} visitor
* @param {boolean | null | undefined} [reverse]
* @returns {undefined}
*
* @param {UnistNode} tree
* Tree to traverse.
* @param {Visitor | Test} test
* `unist-util-is`-compatible test
* @param {Visitor | boolean | null | undefined} [visitor]
* Handle each node.
* @param {boolean | null | undefined} [reverse]
* Traverse in reverse preorder (NRL) instead of the default preorder (NLR).
* @returns {undefined}
* Nothing.
*
* @template {UnistNode} Tree
* Node type.
* @template {Test} Check
* `unist-util-is`-compatible test.
*/
export function visitParents(tree, test, visitor, reverse) {
/** @type {Test} */
let check
if (typeof test === 'function' && typeof visitor !== 'function') {
reverse = visitor
// @ts-expect-error no visitor given, so `visitor` is test.
visitor = test
} else {
// @ts-expect-error visitor given, so `test` isnt a visitor.
check = test
}
const is = convert(check)
const step = reverse ? -1 : 1
factory(tree, undefined, [])()
/**
* @param {UnistNode} node
* @param {number | undefined} index
* @param {Array<UnistParent>} parents
*/
function factory(node, index, parents) {
const value = /** @type {Record<string, unknown>} */ (
node && typeof node === 'object' ? node : {}
)
if (typeof value.type === 'string') {
const name =
// `hast`
typeof value.tagName === 'string'
? value.tagName
: // `xast`
typeof value.name === 'string'
? value.name
: undefined
Object.defineProperty(visit, 'name', {
value:
'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'
})
}
return visit
function visit() {
/** @type {Readonly<ActionTuple>} */
let result = empty
/** @type {Readonly<ActionTuple>} */
let subresult
/** @type {number} */
let offset
/** @type {Array<UnistParent>} */
let grandparents
if (!test || is(node, index, parents[parents.length - 1] || undefined)) {
// @ts-expect-error: `visitor` is now a visitor.
result = toResult(visitor(node, parents))
if (result[0] === EXIT) {
return result
}
}
if ('children' in node && node.children) {
const nodeAsParent = /** @type {UnistParent} */ (node)
if (nodeAsParent.children && result[0] !== SKIP) {
offset = (reverse ? nodeAsParent.children.length : -1) + step
grandparents = parents.concat(nodeAsParent)
while (offset > -1 && offset < nodeAsParent.children.length) {
const child = nodeAsParent.children[offset]
subresult = factory(child, offset, grandparents)()
if (subresult[0] === EXIT) {
return subresult
}
offset =
typeof subresult[1] === 'number' ? subresult[1] : offset + step
}
}
}
return result
}
}
}
/**
* Turn a return value into a clean result.
*
* @param {VisitorResult} value
* Valid return values from visitors.
* @returns {Readonly<ActionTuple>}
* Clean result.
*/
function toResult(value) {
if (Array.isArray(value)) {
return value
}
if (typeof value === 'number') {
return [CONTINUE, value]
}
return value === null || value === undefined ? empty : [value]
}

22
node_modules/unist-util-visit-parents/license generated vendored Normal file
View File

@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2016 Titus Wormer <tituswormer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

101
node_modules/unist-util-visit-parents/package.json generated vendored Normal file
View File

@@ -0,0 +1,101 @@
{
"name": "unist-util-visit-parents",
"version": "6.0.1",
"description": "unist utility to recursively walk over nodes, with ancestral information",
"license": "MIT",
"keywords": [
"unist",
"unist-util",
"util",
"utility",
"tree",
"ast",
"visit",
"traverse",
"walk",
"check",
"parent",
"parents"
],
"repository": "syntax-tree/unist-util-visit-parents",
"bugs": "https://github.com/syntax-tree/unist-util-visit-parents/issues",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
},
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
"contributors": [
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
],
"sideEffects": false,
"type": "module",
"exports": {
".": "./index.js",
"./do-not-use-color": {
"node": "./lib/color.node.js",
"default": "./lib/color.js"
}
},
"types": "index.d.ts",
"files": [
"lib/",
"index.d.ts",
"index.js"
],
"dependencies": {
"@types/unist": "^3.0.0",
"unist-util-is": "^6.0.0"
},
"devDependencies": {
"@types/hast": "^3.0.0",
"@types/mdast": "^4.0.0",
"@types/node": "^20.0.0",
"@types/xast": "^2.0.0",
"c8": "^8.0.0",
"mdast-util-from-markdown": "^1.0.0",
"mdast-util-gfm": "^2.0.0",
"micromark-extension-gfm": "^2.0.0",
"prettier": "^2.0.0",
"remark-cli": "^11.0.0",
"remark-preset-wooorm": "^9.0.0",
"strip-ansi": "^7.0.0",
"tsd": "^0.28.0",
"type-coverage": "^2.0.0",
"typescript": "^5.0.0",
"xo": "^0.54.0"
},
"scripts": {
"prepack": "npm run build && npm run format",
"build": "tsc --build --clean && tsc --build && tsd && type-coverage",
"format": "remark . -qfo && prettier . -w --loglevel warn && xo --fix",
"test-api": "node --conditions development test.js",
"test-coverage": "c8 --100 --reporter lcov npm run test-api",
"test": "npm run build && npm run format && npm run test-coverage"
},
"prettier": {
"bracketSpacing": false,
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"useTabs": false
},
"remarkConfig": {
"plugins": [
"remark-preset-wooorm"
]
},
"typeCoverage": {
"atLeast": 100,
"detail": true,
"#": "needed `any`s",
"ignoreFiles": [
"lib/index.d.ts"
],
"ignoreCatch": true,
"strict": true
},
"xo": {
"prettier": true
}
}

388
node_modules/unist-util-visit-parents/readme.md generated vendored Normal file
View File

@@ -0,0 +1,388 @@
# unist-util-visit-parents
[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]
[![Sponsors][sponsors-badge]][collective]
[![Backers][backers-badge]][collective]
[![Chat][chat-badge]][chat]
[unist][] utility to walk the tree with a stack of parents.
## Contents
* [What is this?](#what-is-this)
* [When should I use this?](#when-should-i-use-this)
* [Install](#install)
* [Use](#use)
* [API](#api)
* [`visitParents(tree[, test], visitor[, reverse])`](#visitparentstree-test-visitor-reverse)
* [`CONTINUE`](#continue)
* [`EXIT`](#exit)
* [`SKIP`](#skip)
* [`Action`](#action)
* [`ActionTuple`](#actiontuple)
* [`BuildVisitor`](#buildvisitor)
* [`Index`](#index)
* [`Test`](#test)
* [`Visitor`](#visitor)
* [`VisitorResult`](#visitorresult)
* [Types](#types)
* [Compatibility](#compatibility)
* [Related](#related)
* [Contribute](#contribute)
* [License](#license)
## What is this?
This is a very important utility for working with unist as it lets you walk the
tree.
## When should I use this?
You can use this utility when you want to walk the tree and want to know about
every parent of each node.
You can use [`unist-util-visit`][unist-util-visit] if you dont care about the
entire stack of parents.
## Install
This package is [ESM only][esm].
In Node.js (version 16+), install with [npm][]:
```sh
npm install unist-util-visit-parents
```
In Deno with [`esm.sh`][esmsh]:
```js
import {visitParents} from 'https://esm.sh/unist-util-visit-parents@6'
```
In browsers with [`esm.sh`][esmsh]:
```html
<script type="module">
import {visitParents} from 'https://esm.sh/unist-util-visit-parents@6?bundle'
</script>
```
## Use
```js
import {visitParents} from 'unist-util-visit-parents'
import {fromMarkdown} from 'mdast-util-from-markdown'
const tree = fromMarkdown('Some *emphasis*, **strong**, and `code`.')
visitParents(tree, 'strong', function (node, ancestors) {
console.log(node.type, ancestors.map(ancestor => ancestor.type))
})
```
Yields:
```js
strong ['root', 'paragraph']
```
## API
This package exports the identifiers [`CONTINUE`][api-continue],
[`EXIT`][api-exit], [`SKIP`][api-skip], and [`visitParents`][api-visitparents].
There is no default export.
### `visitParents(tree[, test], visitor[, reverse])`
Visit nodes, with ancestral information.
This algorithm performs *[depth-first][]* *[tree traversal][tree-traversal]*
in *[preorder][]* (**NLR**) or if `reverse` is given, in *reverse preorder*
(**NRL**).
You can choose for which nodes `visitor` is called by passing a `test`.
For complex tests, you should test yourself in `visitor`, as it will be
faster and will have improved type information.
Walking the tree is an intensive task.
Make use of the return values of the visitor when possible.
Instead of walking a tree multiple times, walk it once, use
[`unist-util-is`][unist-util-is] to check if a node matches, and then perform
different operations.
You can change the tree.
See [`Visitor`][api-visitor] for more info.
###### Parameters
* `tree` ([`Node`][node])
— tree to traverse
* `test` ([`Test`][api-test], optional)
— [`unist-util-is`][unist-util-is]-compatible test
* `visitor` ([`Visitor`][api-visitor])
— handle each node
* `reverse` (`boolean`, default: `false`)
— traverse in reverse preorder (NRL) instead of the default preorder (NLR)
###### Returns
Nothing (`undefined`).
### `CONTINUE`
Continue traversing as normal (`true`).
### `EXIT`
Stop traversing immediately (`false`).
### `SKIP`
Do not traverse this nodes children (`'skip'`).
### `Action`
Union of the action types (TypeScript type).
###### Type
```ts
type Action = typeof CONTINUE | typeof EXIT | typeof SKIP
```
### `ActionTuple`
List with one or two values, the first an action, the second an index
(TypeScript type).
###### Type
```ts
type ActionTuple = [
(Action | null | undefined | void)?,
(Index | null | undefined)?
]
```
### `BuildVisitor`
Build a typed `Visitor` function from a tree and a test (TypeScript type).
It will infer which values are passed as `node` and which as `parents`.
###### Type parameters
* `Tree` ([`Node`][node], default: `Node`)
— tree type
* `Check` ([`Test`][api-test], default: `Test`)
— test type
###### Returns
[`Visitor`][api-visitor].
### `Index`
Move to the sibling at `index` next (after node itself is completely
traversed) (TypeScript type).
Useful if mutating the tree, such as removing the node the visitor is currently
on, or any of its previous siblings.
Results less than `0` or greater than or equal to `children.length` stop
traversing the parent.
###### Type
```ts
type Index = number
```
### `Test`
[`unist-util-is`][unist-util-is] compatible test (TypeScript type).
### `Visitor`
Handle a node (matching `test`, if given) (TypeScript type).
Visitors are free to transform `node`.
They can also transform the parent of node (the last of `ancestors`).
Replacing `node` itself, if `SKIP` is not returned, still causes its
descendants to be walked (which is a bug).
When adding or removing previous siblings of `node` (or next siblings, in
case of reverse), the `Visitor` should return a new `Index` to specify the
sibling to traverse after `node` is traversed.
Adding or removing next siblings of `node` (or previous siblings, in case
of reverse) is handled as expected without needing to return a new `Index`.
Removing the children property of an ancestor still results in them being
traversed.
###### Parameters
* `node` ([`Node`][node])
— found node
* `parents` ([`Array<Node>`][node])
— ancestors of `node`
###### Returns
What to do next.
An `Index` is treated as a tuple of `[CONTINUE, Index]`.
An `Action` is treated as a tuple of `[Action]`.
Passing a tuple back only makes sense if the `Action` is `SKIP`.
When the `Action` is `EXIT`, that action can be returned.
When the `Action` is `CONTINUE`, `Index` can be returned.
### `VisitorResult`
Any value that can be returned from a visitor (TypeScript type).
###### Type
```ts
type VisitorResult =
| Action
| ActionTuple
| Index
| null
| undefined
| void
```
## Types
This package is fully typed with [TypeScript][].
It exports the additional types [`Action`][api-action],
[`ActionTuple`][api-actiontuple], [`BuildVisitor`][api-buildvisitor],
[`Index`][api-index], [`Test`][api-test], [`Visitor`][api-visitor], and
[`VisitorResult`][api-visitorresult].
## Compatibility
Projects maintained by the unified collective are compatible with maintained
versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of
Node.
This means we try to keep the current release line,
`unist-util-visit-parents@^6`, compatible with Node.js 16.
## Related
* [`unist-util-visit`](https://github.com/syntax-tree/unist-util-visit)
— walk the tree with one parent
* [`unist-util-filter`](https://github.com/syntax-tree/unist-util-filter)
— create a new tree with all nodes that pass a test
* [`unist-util-map`](https://github.com/syntax-tree/unist-util-map)
— create a new tree with all nodes mapped by a given function
* [`unist-util-flatmap`](https://gitlab.com/staltz/unist-util-flatmap)
— create a new tree by mapping (to an array) with the given function
* [`unist-util-remove`](https://github.com/syntax-tree/unist-util-remove)
— remove nodes from a tree that pass a test
* [`unist-util-select`](https://github.com/syntax-tree/unist-util-select)
— select nodes with CSS-like selectors
## Contribute
See [`contributing.md`][contributing] in [`syntax-tree/.github`][health] for
ways to get started.
See [`support.md`][support] for ways to get help.
This project has a [code of conduct][coc].
By interacting with this repository, organization, or community you agree to
abide by its terms.
## License
[MIT][license] © [Titus Wormer][author]
<!-- Definition -->
[build-badge]: https://github.com/syntax-tree/unist-util-visit-parents/workflows/main/badge.svg
[build]: https://github.com/syntax-tree/unist-util-visit-parents/actions
[coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/unist-util-visit-parents.svg
[coverage]: https://codecov.io/github/syntax-tree/unist-util-visit-parents
[downloads-badge]: https://img.shields.io/npm/dm/unist-util-visit-parents.svg
[downloads]: https://www.npmjs.com/package/unist-util-visit-parents
[size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=unist-util-visit-parents
[size]: https://bundlejs.com/?q=unist-util-visit-parents
[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg
[backers-badge]: https://opencollective.com/unified/backers/badge.svg
[collective]: https://opencollective.com/unified
[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg
[chat]: https://github.com/syntax-tree/unist/discussions
[npm]: https://docs.npmjs.com/cli/install
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[esmsh]: https://esm.sh
[typescript]: https://www.typescriptlang.org
[license]: license
[author]: https://wooorm.com
[health]: https://github.com/syntax-tree/.github
[contributing]: https://github.com/syntax-tree/.github/blob/HEAD/contributing.md
[support]: https://github.com/syntax-tree/.github/blob/HEAD/support.md
[coc]: https://github.com/syntax-tree/.github/blob/HEAD/code-of-conduct.md
[unist]: https://github.com/syntax-tree/unist
[node]: https://github.com/syntax-tree/unist#node
[depth-first]: https://github.com/syntax-tree/unist#depth-first-traversal
[tree-traversal]: https://github.com/syntax-tree/unist#tree-traversal
[preorder]: https://github.com/syntax-tree/unist#preorder
[unist-util-visit]: https://github.com/syntax-tree/unist-util-visit
[unist-util-is]: https://github.com/syntax-tree/unist-util-is
[api-visitparents]: #visitparentstree-test-visitor-reverse
[api-continue]: #continue
[api-exit]: #exit
[api-skip]: #skip
[api-action]: #action
[api-actiontuple]: #actiontuple
[api-buildvisitor]: #buildvisitor
[api-index]: #index
[api-test]: #test
[api-visitor]: #visitor
[api-visitorresult]: #visitorresult