2021-05-18 17:17:54 +03:00
|
|
|
/*
|
|
|
|
* https://github.com/morethanwords/tweb
|
|
|
|
* Copyright (C) 2019-2021 Eduard Kuzmenko
|
|
|
|
* https://github.com/morethanwords/tweb/blob/master/LICENSE
|
|
|
|
*
|
|
|
|
* Originally from:
|
|
|
|
* https://github.com/zhukov/webogram
|
|
|
|
* Copyright (C) 2014 Igor Zhukov <igor.beatle@gmail.com>
|
|
|
|
* https://github.com/zhukov/webogram/blob/master/LICENSE
|
|
|
|
*/
|
|
|
|
|
2022-04-03 17:04:54 +03:00
|
|
|
import LatinizeMap from "../config/latinizeMap";
|
2021-05-18 17:17:54 +03:00
|
|
|
|
|
|
|
const badCharsRe = /[`~!@#$%^&*()\-_=+\[\]\\|{}'";:\/?.>,<]+/g;
|
|
|
|
const trimRe = /^\s+|\s$/g;
|
|
|
|
|
2021-07-23 22:16:17 +03:00
|
|
|
export function clearBadCharsAndTrim(text: string) {
|
|
|
|
return text.replace(badCharsRe, '').replace(trimRe, '');
|
|
|
|
}
|
|
|
|
|
|
|
|
export function latinizeString(text: string) {
|
|
|
|
return text.replace(/[^A-Za-z0-9]/g, (ch) => {
|
2022-04-03 17:04:54 +03:00
|
|
|
const latinizeCh = LatinizeMap[ch];
|
2021-07-23 22:16:17 +03:00
|
|
|
return latinizeCh !== undefined ? latinizeCh : ch;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-05-18 17:17:54 +03:00
|
|
|
export default function cleanSearchText(text: string, latinize = true) {
|
|
|
|
const hasTag = text.charAt(0) === '%';
|
2021-07-23 22:16:17 +03:00
|
|
|
text = clearBadCharsAndTrim(text);
|
|
|
|
if(latinize) text = latinizeString(text);
|
2021-05-18 17:17:54 +03:00
|
|
|
|
|
|
|
text = text.toLowerCase();
|
2021-07-23 22:16:17 +03:00
|
|
|
if(hasTag) text = '%' + text;
|
|
|
|
|
|
|
|
return text;
|
|
|
|
}
|
|
|
|
|
|
|
|
export type ProcessSearchTextOptions = Partial<{
|
|
|
|
clearBadChars: boolean,
|
|
|
|
latinize: boolean,
|
|
|
|
ignoreCase: boolean,
|
|
|
|
includeTag: boolean
|
|
|
|
}>;
|
2021-05-18 17:17:54 +03:00
|
|
|
|
2021-07-23 22:16:17 +03:00
|
|
|
export function processSearchText(text: string, options: ProcessSearchTextOptions = {}) {
|
|
|
|
const hasTag = options.includeTag && text.charAt(0) === '%';
|
|
|
|
if(options.clearBadChars) text = clearBadCharsAndTrim(text);
|
|
|
|
if(options.latinize) text = latinizeString(text);
|
|
|
|
if(options.ignoreCase) text = text.toLowerCase();
|
|
|
|
if(hasTag) text = '%' + text;
|
2021-05-18 17:17:54 +03:00
|
|
|
return text;
|
|
|
|
}
|