-
Notifications
You must be signed in to change notification settings - Fork 15
/
ModuleLabel.ts
234 lines (195 loc) · 6.88 KB
/
ModuleLabel.ts
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import { useOnMove } from '@/events/useOnMove';
import { avg } from '@/helpers/avg';
import { neighbourGroup } from '@/helpers/neighbourGroup';
import { range } from '@/helpers/range';
import { uniq } from '@/helpers/uniq';
import { StateDto } from '@/models/State';
import { Value } from '@/models/Value';
import { Module } from '@/modules/Module';
import { assert, isFunction } from '@/validation/assert';
export interface ModuleLabelSettings {
/** Formatter used to format values before rendering them as text */
formatter: (realValue: number) => string;
}
/**
* Module showing labels, that are displaying current value as text (by default beneath values).
* - draggable, but not clickable
* - labels merge, when overlapping each-other
* - merged labels are moveable by dragging individual values
* - labels never exceed parent, sticking to one of it's sides
*
* Uses `.jsr_label` CSS class for each label. Hidden labels use `.is-hidden` class.
*
* @note At any point of time, all possible label combinations (single and merged labels) are rendered.
* This is necessary for simpler code, but also for performance reasons. Merging labels is complex topic.
* Those labels, that are computed to not be visible, have `.is-hidden` class appended.
*/
export class ModuleLabel extends Module {
private labels: Map<string, Label> = new Map();
private primaryLabels: string[] = [];
private settings: ModuleLabelSettings;
constructor (settings: Partial<ModuleLabelSettings> = {}) {
super();
this.assertSettings(settings);
this.settings = Object.assign({
formatter: String,
}, settings);
}
public destroy () {
this.labels.forEach(l => l.el.remove());
}
public initView () {
const primaryLabels = getPrimaryLabels(this.config.valuesCount);
const labelGroups = [
primaryLabels,
...getAllNeighourLabels(this.config.valuesCount),
];
const labels = new Map(labelGroups.flat().map(label => {
const el = document.createElement('div');
el.classList.add('jsr_label');
el.dataset.key = label;
el.style.left = '0';
useOnMove(el, (x, trigger) => this.handleMove(label, x, trigger), this.renderer.getContainer());
return [
label,
{ key: label, el } as Label,
];
}));
this.primaryLabels = primaryLabels;
this.labels = labels;
this.labels.forEach(label => this.renderer.addChild(label.el));
}
public render (state: StateDto): VoidFunction {
return () => {
this.applyValues(state);
this.fixExceeding();
this.fixOverlapping();
};
}
private applyValues (state: StateDto) {
for (const [key, label] of this.labels) {
const labels = uniq(key.split('')).map(singleKey => ({
key: singleKey,
value: state.values[Number(singleKey)],
}));
const avgLeftRatio = avg(...labels.map(v => v.value.asRatio()));
const formatValue = (v: Value) => this.settings.formatter(
Number(v.asReal().toFixed(this.config.stepDecimals)),
);
label.el.style.left = `${avgLeftRatio * 100}%`;
label.el.innerHTML = labels.map(
(label, index) => `
<span data-key="${label.key}">
${formatValue(label.value)}
${index < (labels.length - 1) ? ' - ' : ''}
</span>
`,
).join('');
}
}
/**
* @performance
*/
private fixOverlapping () {
const verifiedLabels = verifyVisibleLabels([], this.primaryLabels, this.doLabelsOverlap.bind(this));
[...this.labels.values()].forEach(label => {
if (verifiedLabels.includes(label.key)) {
label.el.classList.remove('is-hidden');
} else {
label.el.classList.add('is-hidden');
}
});
}
/**
* @performance
*/
private fixExceeding () {
const containerRect = this.renderer.getContainer().getBoundingClientRect();
[...this.labels.values()].map(l => l.el).forEach(label => {
const rect = label.getBoundingClientRect();
if (rect.left < containerRect.left) {
const currentLeft = parseFloat(label.style.left);
const correction = this.renderer.distanceToRelative(containerRect.left - rect.left) * 100;
label.style.left = `${currentLeft + correction}%`;
}
if (rect.right > containerRect.right) {
const currentLeft = parseFloat(label.style.left);
const correction = this.renderer.distanceToRelative(rect.right - containerRect.right) * 100;
label.style.left = `${currentLeft - correction}%`;
}
});
}
private handleMove (labelKey: string, x: number, trigger: HTMLElement) {
const ratio = this.renderer.positionToRelative(x);
if (labelKey.length === 1) {
this.input.setRatioValue(Number(labelKey), ratio);
} else {
const movedLabelKey = trigger.dataset.key;
if (!movedLabelKey || movedLabelKey.length > 1) {
return; // @TODO
}
this.input.setRatioValue(Number(movedLabelKey), ratio);
}
}
private doLabelsOverlap (first: string, second: string): boolean {
const firstRect = this.labels.get(first)!.el.getBoundingClientRect();
const secondRect = this.labels.get(second)!.el.getBoundingClientRect();
return firstRect.right > secondRect.left;
}
private assertSettings (settings: Partial<ModuleLabelSettings>) {
settings.formatter && assert('Label.formatter', settings.formatter, isFunction);
}
}
const uniqChars = (str: string) => uniq(str.split('')).join('');
export const getPrimaryLabels = (n: number): string[] => {
if (n === 0) {
return [];
}
if (n === 1) {
return ['0'];
}
return range(n - 1).map(v => v.toString());
};
export const getAllNeighourLabels = (n: number): string[][] => {
// [a, b, c] -> [[ab, bc], [abc]]
const process = (arr: string[]): string[][] => {
// [a, b, c] -> [ab, bc]
const groups = neighbourGroup(arr).map(g => uniqChars(g.join('')));
return [
groups,
...groups.length > 1 ? process(groups) : [],
];
};
return process(getPrimaryLabels(n));
};
export const verifyVisibleLabels = (
verifiedLabels: string[],
labels: string[],
doLabelsOverlap: (first: string, second: string) => boolean,
): string[] => {
const [first, second, ...rest] = labels;
if (!first) {
return verifiedLabels;
} else if (!second) {
return [...verifiedLabels, first];
} else {
if (doLabelsOverlap(first, second)) {
return verifyVisibleLabels(
[],
// labels overlap, so verify if joined label overlaps with previous ones (already verified) or with next (rest)
[...verifiedLabels, uniqChars(first + second), ...rest],
doLabelsOverlap,
);
} else {
return verifyVisibleLabels(
[...verifiedLabels, first], // first label doesn't overlap second, so it's visible
[second, ...rest], // but second label may overlap with third, so pass it further
doLabelsOverlap,
);
}
}
};
interface Label {
key: string;
el: HTMLElement;
}