Skip to content

Commit

Permalink
chore(Forms): clean paths properly when only slash is given as iterat…
Browse files Browse the repository at this point in the history
…ePath (#4021)

Its an edge case, but when using an array iterator with a `/` slash only
to target an array, fields could end up using `//0/something` as the
path.
  • Loading branch information
tujoworker authored Sep 27, 2024
1 parent cc1c365 commit 66ddb48
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,24 @@ describe('usePath', () => {
)
})

it('should clean paths properly when "iteratePath" is just a slash', () => {
const path = '/path'
const iteratePath = '/'
const itemPath = '/itemPath'
const iterateElementIndex = 0
const { result } = renderHook(() => usePath({ path, itemPath }), {
wrapper: ({ children }) => (
<Iterate.Array path={iteratePath} value={['one']}>
{children}
</Iterate.Array>
),
})
expect(result.current.path).toBe(`/${iterateElementIndex}${itemPath}`)
expect(result.current.itemPath).toBe(
`/${iterateElementIndex}${itemPath}`
)
})

it('should return a combined path when Iterate is inside Form.Section', () => {
const path = '/path'
const sectionPath = '/sectionPath'
Expand Down
29 changes: 18 additions & 11 deletions packages/dnb-eufemia/src/extensions/forms/hooks/usePath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,16 @@ export default function usePath(props: Props = {}) {
}

const joinPath = useCallback((paths: Array<Path>) => {
return paths
.reduce((acc, cur) => (cur ? `${acc}/${cur}` : acc), '/')
.replace(/\/{2,}/g, '/')
.replace(/\/+$/, '')
return cleanPath(
paths.reduce((acc, cur) => (cur ? `${acc}/${cur}` : acc), '/')
)
}, [])

const makeSectionPath = useCallback(
(path: Path) => {
return `${
sectionPath && sectionPath !== '/' ? sectionPath : ''
}${path}`.replace(/\/$/, '')
return cleanPath(
`${sectionPath && sectionPath !== '/' ? sectionPath : ''}${path}`
)
},
[sectionPath]
)
Expand All @@ -51,15 +50,17 @@ export default function usePath(props: Props = {}) {
root = makeSectionPath('')
}

return `${root}${iteratePath || ''}/${iterateElementIndex}${
itemPath && itemPath !== '/' ? itemPath : ''
}`
return cleanPath(
`${root}${iteratePath || ''}/${iterateElementIndex}${
itemPath || ''
}`
)
},
[
itemPathProp,
iteratePathProp,
sectionPath,
iterateElementIndex,
itemPathProp,
makeSectionPath,
]
)
Expand Down Expand Up @@ -101,3 +102,9 @@ export default function usePath(props: Props = {}) {
makeSectionPath,
}
}

// Will remove duplicate slashes and trailing slashes
// /foo///bar/// => /foo/bar
function cleanPath(path: Path) {
return path.replace(/\/+$|\/(\/)+/g, '$1')
}

0 comments on commit 66ddb48

Please sign in to comment.