Skip to content
Source
Sign inSign up
TanStack/redact

fix: match React's Children key and traversal semantics #37

OpenVladexy88x(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/37/headopened

Showing 2 changed files with 58 additions and 49 deletions (loading 1).

x
0 of 2 viewed, 2 left
58 additions and 49 deletionspackages/redact/src/react/children.tsModified
View file
@@ -1,53 +1,70 @@
import { isValidElement, cloneElement } from './element'
import type { ReactNode, ReactElement } from '../core'
​
-function flatten(node: ReactNode, out: any[], prefix: string): void {
- if (node == null || typeof node === 'boolean') return
- if (Array.isArray(node)) {
- for (let i = 0; i < node.length; i++) flatten(node[i], out, prefix + '.' + i)
- return
- }
- out.push(node)
+// Keys follow React's Children scheme: '.' separates levels, ':' separates
+// siblings, keyed children use '$' + escaped key instead of their index.
+function escapeKey(key: string): string {
+ return '$' + key.replace(/[=:]/g, (m) => (m === '=' ? '=0' : '=2'))
}
​
-function getKey(node: any, index: number, prefix: string): string {
- if (isValidElement(node) && node.key != null) return prefix + '$' + node.key
- return prefix + ':' + index
+function escapeUserProvidedKey(key: string): string {
+ return key.replace(/\/+/g, '$&/')
​
-function mapChildren(
+function getElementKey(node: any, index: number): string {
+ if (isValidElement(node) && node.key != null) return escapeKey('' + node.key)
+ return index.toString(36)