-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpali.js
109 lines (90 loc) · 2.92 KB
/
pali.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
function onInit() {
const container = document.getElementById('container');
window.pali = new Pali(container, window.jsframedata);
}
function setData(data) {
if (!window.pali) onInit(); // varulta
window.pali.setData(data);
}
function saveData(data) {
window.port2.postMessage({ msg: "datasave", data: { ...data } });
}
function getData() {
return window.pali.getData();
}
function updateData(data) {
window.port2.postMessage({ msg: "update", data: { ...data } });
}
paliTranslations = {
en: {
labelText: "Give a word:", // label text
}
}
class Pali {
constructor(container, data) {
this.settings = {
lang: "fi", // laguage, fi, en
inputChars: 10, // input alueen leveys
minChars: 0, // sanassa tarvittavien merkkien minimimäärä
labelText: "Anna sana:", // labelin teksti
}
if (data) {
const lang = data.params?.lang ?? 'fi';
Object.assign(this.settings, paliTranslations[lang] ?? {}, );
Object.assign(this.settings, data.params);
}
this.container = container;
this.createContent();
}
createContent() {
const s = this.settings;
const label = document.createElement('label');
label.htmlFor = 'word';
label.textContent = label.textContent = s.labelText.replace('${count}', s.minChars);
this.container.appendChild(label);
const input = document.createElement('input');
input.type = 'text';
input.id = 'word';
input.name = 'word';
input.style.width = s.inputChars + 'ch';
this.container.appendChild(input);
const icon = document.createElement('span');
icon.className = 'icon';
this.container.appendChild(icon);
this.input = input;
this.icon = icon;
this.input.addEventListener('input', () => this.checkPalindrome());
this.input.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
saveData(this.getData());
}
});
}
checkPalindrome() {
const word = this.input.value;
let isPalindrome = true;
for (let i = 0, j = word.length - 1; i < j; i++, j--) {
if (word[i] !== word[j]) {
isPalindrome = false;
break;
}
}
if (isPalindrome && this.settings.minChars <= word.length) {
this.icon.textContent = '✔';
this.icon.style.color = 'green';
} else {
this.icon.textContent = '✘';
this.icon.style.color = 'red';
}
updateData(getData());
}
getData() {
return { c: { text: this.input.value } };
}
setData(data) {
const newText = data.c.text;
if (this.input.value === newText) return;
this.input.value = newText;
this.checkPalindrome();
}
}