keeweb/app/scripts/util/formatting/password-presenter.js

69 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-03-21 12:24:21 +01:00
import 'util/kdbxweb/protected-value-ex';
2019-09-27 07:37:26 +02:00
import { shuffle } from 'util/fn';
class RandomNameGenerator {
randomCharCode() {
return 97 + Math.floor(Math.random() * 26);
}
}
function charCodeToHtml(char) {
return Math.random() < 0.2 ? String.fromCharCode(char) : `&#x${char.toString(16)};`;
}
const PasswordPresenter = {
present(length) {
return new Array(length + 1).join('•');
},
presentValueWithLineBreaks(value) {
if (!value) {
return '';
}
let result = '';
2020-06-01 16:53:51 +02:00
value.forEachChar((ch) => {
2019-09-27 07:37:26 +02:00
result += ch === 10 ? '\n' : '•';
});
return result;
},
2020-04-02 16:27:10 +02:00
asDOM(value) {
const items = [];
2019-09-27 07:37:26 +02:00
const gen = new RandomNameGenerator();
let ix = 0;
2020-06-01 16:53:51 +02:00
value.forEachChar((char) => {
2019-09-27 07:37:26 +02:00
const charHtml = charCodeToHtml(char);
2020-04-02 16:27:10 +02:00
items.push({ html: charHtml, order: ix });
2019-09-27 07:37:26 +02:00
if (Math.random() > 0.5) {
const fakeChar = gen.randomCharCode();
const fakeCharHtml = charCodeToHtml(fakeChar);
2020-04-02 16:27:10 +02:00
items.push({ html: fakeCharHtml, order: -1 });
2019-09-27 07:37:26 +02:00
}
ix++;
});
2020-04-02 16:27:10 +02:00
shuffle(items);
const topEl = document.createElement('div');
topEl.style.display = 'flex';
for (const item of items) {
const el = document.createElement('div');
el.innerHTML = item.html;
if (item.order >= 0) {
el.style.order = item.order;
} else {
el.style.display = 'none';
}
topEl.appendChild(el);
}
2019-09-27 07:37:26 +02:00
2020-04-02 16:27:10 +02:00
return topEl;
2019-09-27 07:37:26 +02:00
}
};
export { PasswordPresenter };