receptor/src/search.js

68 lines
1.8 KiB
JavaScript
Raw Normal View History

2017-12-30 19:06:59 +01:00
import numeral from "numeral";
2018-02-11 03:18:29 +01:00
import query from 'query-string';
import { filter_subscribe } from './actions/filter_subscribe';
import { push_query } from './actions/routing';
2017-12-30 19:06:59 +01:00
// via https://stackoverflow.com/a/46946490
const ssplit = str => str.match(/\\?.|^$/g).reduce((p, c) => {
if (c === '"') {
p.quote ^= 1;
} else if (!p.quote && c === ' ') {
p.a.push('');
} else {
p.a[p.a.length-1] += c.replace(/\\(.)/,"$1");
}
return p;
}, {a: ['']}).a;
2018-02-11 03:18:29 +01:00
export function search_criteria(text) {
2017-12-30 19:06:59 +01:00
if (!text) {
return [];
}
const terms = ssplit(text);
const operators = [":", "==", "!=", ">", ">=", "<", "<="];
return terms.map(t => operators.reduce((a, op) => {
if (t.indexOf(op) === -1) {
return a;
}
const [field, value] = t.split(op);
if (op == ":") {
2018-03-14 08:22:56 +01:00
if (field == "tracker") {
return { op: "has", field: "tracker_urls", value };
}
return { op: "ilike", field, value };
2017-12-30 19:06:59 +01:00
}
if (!isNaN(numeral(value).value())) {
return {
op,
field,
value: numeral(value).value()
};
}
return { op, field, value };
}, null) || {
field: "name",
op: "ilike",
value: `%${t}%`
}
);
}
2018-02-11 03:18:29 +01:00
export function search_qs(text) {
const qs = query.stringify({
...query.parse(location.search),
s: text || undefined
});
return `${
location.pathname === "/" ? location.pathname : ""
}${qs && "?" + qs}`;
}
export function update_filter(text, fs, location, dispatch) {
// there will always be one torrent filter
const tfilter = fs.filter(fs => fs.kind === "torrent")[0];
const criteria = search_criteria(text);
dispatch(filter_subscribe("torrent", criteria, tfilter.serial));
dispatch(push_query(search_qs(text)));
}