-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmap.js
More file actions
92 lines (85 loc) · 2.72 KB
/
map.js
File metadata and controls
92 lines (85 loc) · 2.72 KB
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
import Translation from 'src/structures/constants/translation.js';
import Setting from './array.js';
export default class MapList extends Setting {
constructor(name = 'map') {
super(name);
}
default() {
return new Map();
}
/**
* @param {Map<string, string>} val
*/
element(val, update, { container, key: setting }) {
const data = [...val.entries()];
function invalid(text) {
return data.some(([value]) => value === text);
}
function add(value, i) {
function save(remove) {
if (remove) data.splice(data.indexOf(value), 1);
update(data.filter(([key]) => key));
}
container.append(createItem({ value, save, invalid, key: `${setting}.${i}` }));
}
data.forEach(add);
let entries = data.length;
return $('<button class="btn btn-success glyphicon glyphicon-plus">').on('click', () => {
const item = ['', ''];
data.push(item);
add(item, entries);
entries += 1;
});
}
encode(value = []) {
if (value instanceof Map) {
return super.encode([...value.entries()]);
}
return super.encode(value);
}
styles() {
return [
'{ border-top: 1px solid white; border-bottom: 1px solid white; padding: 5px 0; }',
'label { align-self: flex-end; }',
'.btn { padding: 3px 6px; }',
'.item { display: inline-flex; flex-wrap: wrap; align-items: center; padding-top: 5px; width: 100%; }',
'.item > * { margin: 0 5px; }',
'.error [id]:not([id$=".value"]) { border-color: red; }',
'.warning { display: none; color: red; flex-basis: 100%; user-select: none; }',
'.error .warning { display: block; }',
];
}
value(value) {
return new Map(super.value(value));
}
}
function createItem({
value = ['key', 'value'],
save,
invalid,
key,
}) {
const left = $('<input type="text">').val(value[0]).on('blur', () => {
const newVal = left.val();
const isInvalid = newVal !== value[0] && invalid(newVal);
left.parent().toggleClass('error', isInvalid);
if (isInvalid || newVal === value[0]) return;
value[0] = newVal;
save();
}).attr('id', key);
const right = $('<input type="text">').val(value[1]).on('blur', () => {
const newVal = right.val();
if (newVal === value[1]) return;
value[1] = newVal;
save();
}).attr('id', `${key}.value`);
const button = $('<button class="btn btn-danger glyphicon glyphicon-trash">').on('click', () => {
save(true);
button.parent().remove();
});
const warning = $('<div class="warning clickable">')
.text(Translation.Setting('map.duplicate'))
.on('click', () => left.val(value[0])
.parent().removeClass('error'));
return $('<div class="item">').append(left, ' : ', right, button, warning);
}