keeweb/app/scripts/auto-type/auto-type-filter.js

101 lines
3.1 KiB
JavaScript
Raw Normal View History

2016-07-25 20:27:22 +02:00
'use strict';
2016-08-02 22:10:05 +02:00
const EntryCollection = require('../collections/entry-collection');
2016-08-14 19:25:23 +02:00
let urlPartsRegex = /^(\w+:\/\/)?(?:www\.)?([^\/]+)\/?(.*)/;
2016-08-02 22:10:05 +02:00
2016-07-25 20:27:22 +02:00
let AutoTypeFilter = function(windowInfo, appModel) {
this.title = windowInfo.title;
this.url = windowInfo.url;
this.text = '';
this.ignoreWindowInfo = false;
this.appModel = appModel;
};
AutoTypeFilter.prototype.getEntries = function() {
2016-07-31 20:38:08 +02:00
let filter = {
text: this.text
};
2016-08-02 22:10:05 +02:00
let entries = this.appModel.getEntriesByFilter(filter);
if (!this.ignoreWindowInfo && this.hasWindowInfo()) {
this.prepareFilter();
entries = new EntryCollection(entries
.map(e => [e, this.getEntryRank(e)])
.filter(e => e[1])
.sort((x, y) => x[1] === y[1] ? x[0].title.localeCompare(y[0].title) : y[1] - x[1])
2016-08-03 19:20:50 +02:00
.map(p => p[0]));
2016-08-02 22:10:05 +02:00
} else {
entries.sortEntries('title');
}
return entries;
};
AutoTypeFilter.prototype.hasWindowInfo = function() {
return this.title || this.url;
};
AutoTypeFilter.prototype.prepareFilter = function() {
this.titleLower = this.title ? this.title.toLowerCase() : null;
this.urlLower = this.url ? this.url.toLowerCase() : null;
2016-08-03 19:20:50 +02:00
this.urlParts = this.url ? urlPartsRegex.exec(this.urlLower) : null;
2016-08-02 22:10:05 +02:00
};
AutoTypeFilter.prototype.getEntryRank = function(entry) {
let rank = 0;
if (this.titleLower && entry.title) {
rank += this.getStringRank(entry.title.toLowerCase(), this.titleLower);
}
if (this.urlParts && entry.url) {
let entryUrlParts = urlPartsRegex.exec(entry.url.toLowerCase());
if (entryUrlParts) {
// domain
if (entryUrlParts[2] === this.urlParts[2]) {
rank += 10;
// path
2016-08-02 22:34:00 +02:00
if (entryUrlParts[3] === this.urlParts[3]) {
rank += 10;
} else if (entryUrlParts[3] && this.urlParts[3]) {
if (entryUrlParts[3].lastIndexOf(this.urlParts[3], 0) === 0) {
rank += 5;
} else if (this.urlParts.lastIndexOf(entryUrlParts[3], 0) === 0) {
rank += 3;
}
}
2016-08-02 22:10:05 +02:00
// scheme
if (entryUrlParts[1] === this.urlParts[1]) {
2016-08-02 22:34:00 +02:00
rank += 1;
2016-08-02 22:10:05 +02:00
}
} else {
if (entry.searchText.indexOf(this.urlLower) >= 0) {
// the url is in some field; include it
rank += 5;
} else {
// another domain; don't show this record at all, ignore title match
return 0;
}
}
}
}
return rank;
};
AutoTypeFilter.prototype.getStringRank = function(s1, s2) {
let ix = s1.indexOf(s2);
if (ix === 0 && s1.length === s2.length) {
return 10;
} else if (ix === 0) {
return 5;
} else if (ix > 0) {
return 3;
}
ix = s2.indexOf(s1);
if (ix === 0) {
return 5;
} else if (ix > 0) {
return 3;
2016-07-31 20:38:08 +02:00
}
2016-08-02 22:10:05 +02:00
return 0;
2016-07-25 20:27:22 +02:00
};
module.exports = AutoTypeFilter;