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[] = [] let results: SearchResult[] = []
traverse(data, function (value, path, root) { traverse(data, function (value, path, root) {
// search in values // check property name
if (value.type === 'value') { const prop = last(path)
if (containsCaseInsensitive(value.value, text)) {
results.push({
dataPath: path,
type: 'value'
})
}
}
// search object property names if (typeof prop === 'string' && containsCaseInsensitive(prop, text)) {
if (value.type === 'Object') { // only add search result when this is an object property name,
value.props.forEach((prop) => { // don't add search result for array indices
if (containsCaseInsensitive(prop.name, text)) { const parentPath = path.slice(0, path.length - 1)
results.push({ const parent = getIn(root, toDataPath(data, parentPath))
dataPath: path.concat(prop.name), if (parent.type === 'Object') {
type: 'property' 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 return results
@ -797,3 +795,10 @@ export function compileJSONPointer (path) {
.map(p => '/' + String(p).replace(/~/g, '~0').replace(/\//g, '~1')) .map(p => '/' + String(p).replace(/~/g, '~0').replace(/\//g, '~1'))
.join('') .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: { value: {
type: 'value', type: 'value',
value: 4, value: 4,
searchProperty: 'normal' searchProperty: 'active'
} }
} }
] ]
@ -302,7 +302,7 @@ const JSON_DATA_EXAMPLE_SEARCH_L = {
value: { value: {
type: 'value', type: 'value',
value: null, value: null,
searchProperty: 'active', searchProperty: 'normal',
searchValue: 'normal' searchValue: 'normal'
} }
}, },
@ -925,11 +925,11 @@ test('search', t => {
// console.log(searchResults) // console.log(searchResults)
t.deepEqual(searchResults, [ t.deepEqual(searchResults, [
{dataPath: ['nill'], type: 'property'},
{dataPath: ['bool'], type: 'property'},
{dataPath: ['obj', 'arr', '2', 'last'], type: 'property'}, {dataPath: ['obj', 'arr', '2', 'last'], type: 'property'},
{dataPath: ['str'], type: 'value'}, {dataPath: ['str'], type: 'value'},
{dataPath: ['nill'], type: 'property'},
{dataPath: ['nill'], type: 'value'}, {dataPath: ['nill'], type: 'value'},
{dataPath: ['bool'], type: 'property'},
{dataPath: ['bool'], type: 'value'} {dataPath: ['bool'], type: 'value'}
]) ])