Fixed ordering of search results

This commit is contained in:
jos 2016-12-30 10:52:48 +01:00
parent aa4b963592
commit 198e8edf85
2 changed files with 28 additions and 23 deletions

View File

@ -517,27 +517,25 @@ export function search (data, text): SearchResult[] {
let results: SearchResult[] = []
traverse(data, function (value, path, root) {
// search in values
if (value.type === 'value') {
if (containsCaseInsensitive(value.value, text)) {
results.push({
dataPath: path,
type: 'value'
})
}
}
// check property name
const prop = last(path)
// search object property names
if (value.type === 'Object') {
value.props.forEach((prop) => {
if (containsCaseInsensitive(prop.name, text)) {
results.push({
dataPath: path.concat(prop.name),
type: 'property'
})
}
})
if (typeof prop === 'string' && containsCaseInsensitive(prop, text)) {
// only add search result when this is an object property name,
// don't add search result for array indices
const parentPath = path.slice(0, path.length - 1)
const parent = getIn(root, toDataPath(data, parentPath))
if (parent.type === 'Object') {
results.push({ dataPath: path, type: 'property' })
}
}
// check value
if (value.type === 'value') {
if (containsCaseInsensitive(value.value, text)) {
results.push({ dataPath: path, type: 'value' })
}
}
})
return results
@ -797,3 +795,10 @@ export function compileJSONPointer (path) {
.map(p => '/' + String(p).replace(/~/g, '~0').replace(/\//g, '~1'))
.join('')
}
/**
* Returns the last item of an array
*/
function last (array: Array): any {
return array[array.length - 1]
}

View File

@ -278,7 +278,7 @@ const JSON_DATA_EXAMPLE_SEARCH_L = {
value: {
type: 'value',
value: 4,
searchProperty: 'normal'
searchProperty: 'active'
}
}
]
@ -302,7 +302,7 @@ const JSON_DATA_EXAMPLE_SEARCH_L = {
value: {
type: 'value',
value: null,
searchProperty: 'active',
searchProperty: 'normal',
searchValue: 'normal'
}
},
@ -925,11 +925,11 @@ test('search', t => {
// console.log(searchResults)
t.deepEqual(searchResults, [
{dataPath: ['nill'], type: 'property'},
{dataPath: ['bool'], type: 'property'},
{dataPath: ['obj', 'arr', '2', 'last'], type: 'property'},
{dataPath: ['str'], type: 'value'},
{dataPath: ['nill'], type: 'property'},
{dataPath: ['nill'], type: 'value'},
{dataPath: ['bool'], type: 'property'},
{dataPath: ['bool'], type: 'value'}
])