Skip to content

Commit

Permalink
feat: Handle files and folders title conflict (fix #57) (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
hugoattal authored Mar 22, 2022
1 parent d35df88 commit 4d21425
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 5 deletions.
61 changes: 61 additions & 0 deletions packages/histoire/src/node/tree.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,65 @@ describe('makeTree', () => {
{ title: 'hi', index: 0 },
])
})

test('should handle title conflict', () => {
const config = getDefaultConfig()
const files = [
{ index: 0, path: ['hi'] },
{ index: 1, path: ['hi'] },
{ index: 2, path: ['hi'] },
]

const tree = makeTree(config, files)

expect(tree).toEqual([
{ title: 'hi', index: 0 },
{ title: 'hi-1', index: 1 },
{ title: 'hi-2', index: 2 },
])
})

test('should handle file-folder conflict when folder in first', () => {
const config = getDefaultConfig()
const files = [
{ index: 0, path: ['hi', 'dad'] },
{ index: 1, path: ['hi'] },
{ index: 2, path: ['hi', 'mom'] },
]

const tree = makeTree(config, files)

expect(tree).toEqual([
{
title: 'hi',
children: [
{ title: 'dad', index: 0 },
{ title: 'mom', index: 2 },
],
},
{ title: 'hi-1', index: 1 },
])
})

test('should handle file-folder conflict when file in first', () => {
const config = getDefaultConfig()
const files = [
{ index: 0, path: ['hi'] },
{ index: 1, path: ['hi', 'dad'] },
{ index: 2, path: ['hi', 'mom'] },
]

const tree = makeTree(config, files)

expect(tree).toEqual([
{
title: 'hi',
children: [
{ title: 'dad', index: 1 },
{ title: 'mom', index: 2 },
],
},
{ title: 'hi-1', index: 0 },
])
})
})
34 changes: 29 additions & 5 deletions packages/histoire/src/node/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,41 @@ export function makeTree (config: HistoireConfig, files: { path: string[], index

return buildTree(treeObject)

// Undefined behavior for folder and file that share the same name under the same directory
function setPath (path: string[], value: unknown, tree: unknown) {
path.reduce((subtree, key, i) => {
if (!subtree[key]) {
subtree[key] = {}
}
if (i === path.length - 1) {
subtree[key] = value
setKey(subtree, key, value)
} else if (isLeaf(subtree[key])) {
setKey(subtree, key, subtree[key])
subtree[key] = {}
} else if (!subtree[key]) {
subtree[key] = {}
}
return subtree[key]
}, tree)

function isLeaf (element) {
return !isNaN(element)
}
}

function setKey (tree, key, value) {
if (isUndefined(tree[key])) {
tree[key] = value
return
}

let copyNumber = 1

while (!isUndefined(tree[`${key}-${copyNumber}`])) {
copyNumber++
}

tree[`${key}-${copyNumber}`] = value

function isUndefined (element) {
return element === undefined
}
}

function buildTree (treeObject: ITreeObject): Tree {
Expand Down

0 comments on commit 4d21425

Please sign in to comment.