debian-mirror-gitlab/app/assets/javascripts/filtered_search/filtered_search_tokenizer.js

67 lines
1.9 KiB
JavaScript
Raw Normal View History

2017-09-10 17:25:29 +05:30
import './filtered_search_token_keys';
2017-08-17 22:00:37 +05:30
2018-03-27 19:54:05 +05:30
export default class FilteredSearchTokenizer {
2017-09-10 17:25:29 +05:30
static processTokens(input, allowedKeys) {
2020-03-13 15:44:24 +05:30
// Regex extracts `(token):(operator)(symbol)(value)`
2017-08-17 22:00:37 +05:30
// Values that start with a double quote must end in a double quote (same for single)
2020-03-13 15:44:24 +05:30
2018-12-13 13:39:08 +05:30
const tokenRegex = new RegExp(
2020-03-13 15:44:24 +05:30
`(${allowedKeys.join('|')}):(=|!=)?([~%@]?)(?:('[^']*'{0,1})|("[^"]*"{0,1})|(\\S+))`,
2018-12-13 13:39:08 +05:30
'g',
);
2017-08-17 22:00:37 +05:30
const tokens = [];
const tokenIndexes = []; // stores key+value for simple search
let lastToken = null;
2018-12-13 13:39:08 +05:30
const searchToken =
input
2020-03-13 15:44:24 +05:30
.replace(tokenRegex, (match, key, operator, symbol, v1, v2, v3) => {
2018-12-13 13:39:08 +05:30
let tokenValue = v1 || v2 || v3;
let tokenSymbol = symbol;
let tokenIndex = '';
2020-03-13 15:44:24 +05:30
let tokenOperator = operator;
2018-12-13 13:39:08 +05:30
if (tokenValue === '~' || tokenValue === '%' || tokenValue === '@') {
tokenSymbol = tokenValue;
tokenValue = '';
}
2020-03-13 15:44:24 +05:30
if (tokenValue === '!=' || tokenValue === '=') {
tokenOperator = tokenValue;
tokenValue = '';
}
2018-12-13 13:39:08 +05:30
tokenIndex = `${key}:${tokenValue}`;
// Prevent adding duplicates
if (tokenIndexes.indexOf(tokenIndex) === -1) {
tokenIndexes.push(tokenIndex);
tokens.push({
key,
value: tokenValue || '',
symbol: tokenSymbol || '',
2020-03-13 15:44:24 +05:30
operator: tokenOperator || '',
2018-12-13 13:39:08 +05:30
});
}
return '';
})
.replace(/\s{2,}/g, ' ')
.trim() || '';
2017-08-17 22:00:37 +05:30
if (tokens.length > 0) {
const last = tokens[tokens.length - 1];
2020-03-13 15:44:24 +05:30
const lastString = `${last.key}:${last.operator}${last.symbol}${last.value}`;
2018-12-13 13:39:08 +05:30
lastToken =
input.lastIndexOf(lastString) === input.length - lastString.length ? last : searchToken;
2017-08-17 22:00:37 +05:30
} else {
lastToken = searchToken;
}
return {
tokens,
lastToken,
searchToken,
};
}
}