Skip to content

Commit

Permalink
fix: allow suffix after param [id]_s
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Apr 27, 2023
1 parent d803831 commit f0fcc07
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
19 changes: 19 additions & 0 deletions src/core/tree.spec.ts
Expand Up @@ -38,6 +38,25 @@ describe('Tree', () => {
expect(child.children.size).toBe(0)
})

it('separate param names from static segments', () => {
const tree = createPrefixTree(DEFAULT_OPTIONS)
tree.insert('[id]_a')
tree.insert('[a]e[b]f')
expect(tree.children.get('[id]_a')!.value).toMatchObject({
rawSegment: '[id]_a',
params: [{ paramName: 'id' }],
path: '/:id()_a',
_type: TreeNodeType.param,
})

expect(tree.children.get('[a]e[b]f')!.value).toMatchObject({
rawSegment: '[a]e[b]f',
params: [{ paramName: 'a' }, { paramName: 'b' }],
path: '/:a()e:b()f',
_type: TreeNodeType.param,
})
})

it('creates params in nested files', () => {
const tree = createPrefixTree(DEFAULT_OPTIONS)
const nestedId = tree.insert('nested/[id].vue')
Expand Down
19 changes: 16 additions & 3 deletions src/core/treeNodeValue.ts
Expand Up @@ -229,6 +229,8 @@ export interface ParseSegmentOptions {
dotNesting?: boolean
}

const IS_VARIABLE_CHAR_RE = /[0-9a-zA-Z_]/

/**
* Parses a segment into the route path segment and the extracted params.
*
Expand All @@ -246,6 +248,11 @@ function parseSegment(
const subSegments: SubSegment[] = []
let currentTreeRouteParam: TreeRouteParam = createEmptyRouteParam()

// position in segment
let pos = 0
// current char
let c: string

function consumeBuffer() {
if (state === ParseSegmentState.static) {
// add the buffer to the path segment as is
Expand All @@ -262,7 +269,13 @@ function parseSegment(
: ''
buffer = ''
pathSegment += `:${currentTreeRouteParam.paramName}${
currentTreeRouteParam.isSplat ? '(.*)' : ''
currentTreeRouteParam.isSplat
? '(.*)'
: // Only append () if necessary
pos < segment.length - 1 && IS_VARIABLE_CHAR_RE.test(segment[pos + 1])
? '()'
: // allow routes like /[id]_suffix to make suffix static and not part of the param
''
}${currentTreeRouteParam.modifier}`
params.push(currentTreeRouteParam)
subSegments.push(currentTreeRouteParam)
Expand All @@ -271,8 +284,8 @@ function parseSegment(
buffer = ''
}

for (let pos = 0; pos < segment.length; pos++) {
const c = segment[pos]
for (pos = 0; pos < segment.length; pos++) {
c = segment[pos]

if (state === ParseSegmentState.static) {
if (c === '[') {
Expand Down

0 comments on commit f0fcc07

Please sign in to comment.