forked from Makar8000/LimitBreakStats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
limitbreak.js
662 lines (573 loc) · 19 KB
/
limitbreak.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
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
'use strict';
const overlaySettingsKey = 'limitbreak-tracker-settings';
const lbLogCode = '36';
const resetLine = { line: [lbLogCode, undefined, '0000', '1', '0000', '1'] };
// Setting keys
const textOptions = {
'None': 'None',
'Current LB': 'CurrentLB',
'Time to Next Bar': 'TimeToBar',
'Time to Full': 'TimeToMax',
'Counters (Unknown / Survival / Passive)': 'LBCounts',
'Passive Ticks': 'PassiveTicks',
'Surviving Lethals': 'SurviveLethals',
'Critical HP Heals': 'CritHeals',
'Unknown Sources': 'UnknownSource',
};
function getOptionsForKeys(validKeys) {
let options = {};
for (const [value, key] of Object.entries(textOptions)) {
if (!validKeys.includes(key))
continue;
options[value] = key;
}
return options;
}
const validSelectKeys = ['None', 'CurrentLB', 'TimeToBar', 'TimeToMax', 'LBCounts'];
const selectOptions = getOptionsForKeys(validSelectKeys);
const validDetailKeys = ['CurrentLB', 'TimeToBar', 'TimeToMax', 'SurviveLethals', 'PassiveTicks', 'UnknownSource'];
const detailOptions = getOptionsForKeys(validDetailKeys);
// Format Type enum
const FormatType = {
Raw: 0,
Separators: 1,
Simplify3: 2,
Simplify4: 3,
Simplify5: 4,
};
// Formatting options specific to key. Currently unused.
const formatOptionsByKey = {
CurrentLB: {
maximumFractionDigits: 0,
},
};
// Auto-generate number formatting options.
const formatOptions = (() => {
const defaultValue = 12345;
const defaultKey = 'CurrentLB';
let formatOptions = {};
for (const typeName in FormatType) {
const type = FormatType[typeName];
formatOptions[formatNumber(defaultValue, type, defaultKey)] = type;
}
return formatOptions;
})();
const configStructure = [
{
id: 'leftText',
name: 'Left Text',
type: 'select',
options: selectOptions,
default: 'CurrentLB',
headerBefore: 'Horizonal Mode Options',
},
{
id: 'middleText',
name: 'Middle Text',
options: selectOptions,
type: 'select',
default: 'TimeToBar',
},
{
id: 'rightText',
name: 'Right Text',
options: selectOptions,
type: 'select',
default: 'LBCounts',
},
{
id: 'hModeBarHeight',
name: 'Container Height',
type: 'text',
default: 18,
},
{
id: 'hModeBarWidth',
name: 'Container Width',
type: 'text',
default: 300,
},
{
id: 'vModeBarHeight',
name: 'Container Height',
type: 'text',
default: 120,
headerBefore: 'Vertical Mode Options',
},
{
id: 'vModeBarWidth',
name: 'Container Width',
type: 'text',
default: 180,
},
{
id: 'showBar',
name: 'Horizontal Mode',
type: 'checkbox',
default: true,
headerBefore: 'Global Options',
},
{
id: 'numberFormat',
name: 'Number Format',
type: 'select',
options: formatOptions,
default: FormatType.Separators,
},
{
id: 'isRounded',
name: 'Rounded Corners',
type: 'checkbox',
default: true,
},
{
id: 'borderSize',
name: 'Border Width',
type: 'text',
default: 1,
},
{
id: 'borderColor',
name: 'Border Color',
type: 'text',
default: 'black',
},
{
id: 'bgColor',
name: 'Background Color',
type: 'text',
default: 'rgba(0, 0, 0, 0.6)',
},
{
id: 'fontSize',
name: 'Font Size',
type: 'text',
default: 14,
},
{
id: 'fontFamily',
name: 'Font Family',
type: 'text',
default: 'Tahoma',
},
{
id: 'fontColor',
name: 'Font Color',
type: 'text',
default: 'white',
}
];
// Return "str px" if "str" is a number, otherwise "str".
function defaultAsPx(str) {
if (parseFloat(str) == str)
return str + 'px';
return str;
}
// Simplifies a number to number of |digits|.
// e.g. num=123456789, digits=3 => 123M
// e.g. num=123456789, digits=4 => 123.4M
// e.g. num=-0.1234567, digits=3 => -0.123
function formatNumberSimplify(num, options, digits) {
// The leading zero does not count.
if (num < 1)
digits++;
// Digits before the decimal.
let originalDigits = Math.max(Math.floor(Math.log10(num)), 0) + 1;
let separator = Math.floor((originalDigits - 1) / 3) * 3;
let suffix = {
0: '',
3: 'k',
6: 'M',
9: 'B',
12: 'T',
15: 'Q',
}[separator];
num /= Math.pow(10, separator);
let finalDigits = originalDigits - separator;
// At least give 3 digits here even if requesting 2.
let decimalPlacesNeeded = Math.max(digits - finalDigits, 0);
// If this is a real decimal place, bound by the per-key formatting options.
if (separator === 0) {
if (typeof options.minimumFractionDigits !== 'undefined')
decimalPlacesNeeded = Math.max(options.minimumFractionDigits, decimalPlacesNeeded);
if (typeof options.maximumFractionDigits !== 'undefined')
decimalPlacesNeeded = Math.min(options.maximumFractionDigits, decimalPlacesNeeded);
}
let shift = Math.pow(10, decimalPlacesNeeded);
num = Math.floor(num * shift) / shift;
return num.toLocaleString('en-US', {
minimumFractionDigits: decimalPlacesNeeded,
maximumFractionDigits: decimalPlacesNeeded,
}) + suffix;
}
function formatNumber(num, format, key) {
let floatNum = parseFloat(num);
if (isNaN(floatNum))
return num;
num = floatNum;
const options = formatOptionsByKey[key] ? formatOptionsByKey[key] : {};
const minDigits = options.minimumFractionDigits > 0 ? options.minimumFractionDigits : 0;
switch (parseInt(format)) {
default:
case FormatType.Raw:
return num.toFixed(minDigits);
case FormatType.Separators:
return num.toLocaleString('en-US', options);
case FormatType.Simplify3:
return formatNumberSimplify(num, options, 3);
case FormatType.Simplify4:
return formatNumberSimplify(num, options, 4);
case FormatType.Simplify5:
return formatNumberSimplify(num, options, 5);
}
}
class BarUI {
constructor(topLevelOptions, div) {
this.options = topLevelOptions;
this.div = div;
this.limitBreakHistory = new LimitBreakHistory();
// Map of keys to elements that contain those values.
// built from this.options.elements.
this.elementMap = {};
if (this.options.showBar) {
// Horizontal Mode
this.div.classList.remove('bar-vertical');
this.div.style.height = defaultAsPx(this.options.hModeBarHeight);
this.div.style.width = defaultAsPx(this.options.hModeBarWidth);
const textMap = {
left: this.options.leftText,
center: this.options.middleText,
right: this.options.rightText,
};
for (const [justifyKey, text] of Object.entries(textMap)) {
if (!validSelectKeys.includes(text))
continue;
let textDiv = document.createElement('div');
textDiv.classList.add(text);
textDiv.style.justifySelf = justifyKey;
this.div.appendChild(textDiv);
this.elementMap[text] = this.elementMap[text] || [];
this.elementMap[text].push(textDiv);
}
} else {
// Vertical Mode
this.div.classList.add('bar-vertical');
this.div.style.height = defaultAsPx(this.options.vModeBarHeight);
this.div.style.width = defaultAsPx(this.options.vModeBarWidth);
for (const [value, key] of Object.entries(detailOptions)) {
if (!validDetailKeys.includes(key))
continue;
// Add label
let labelDiv = document.createElement('div');
const labelKey = `${key}-label`;
labelDiv.classList.add(labelKey);
labelDiv.style.justifySelf = 'left';
labelDiv.innerText = `${value}:`;
this.div.appendChild(labelDiv);
this.elementMap[labelKey] = this.elementMap[labelKey] || [];
this.elementMap[labelKey].push(labelDiv);
// Add value
let textDiv = document.createElement('div');
textDiv.classList.add(key);
textDiv.style.justifySelf = 'right';
this.div.appendChild(textDiv);
this.elementMap[key] = this.elementMap[key] || [];
this.elementMap[key].push(textDiv);
}
}
if (this.options.isRounded)
this.div.classList.add('rounded');
else
this.div.classList.remove('rounded');
let borderStyle = defaultAsPx(this.options.borderSize);
borderStyle += ' solid ' + this.options.borderColor;
this.div.style.border = borderStyle;
this.div.style.fontSize = defaultAsPx(this.options.fontSize);
this.div.style.fontFamily = this.options.fontFamily;
this.div.style.color = this.options.fontColor;
this.div.style.background = this.options.bgColor;
// Alignment hack:
// align-self:center doesn't work when children are taller than parents.
// TODO: is there some better way to do this?
const containerHeight = parseInt(this.div.clientHeight);
for (const el in this.elementMap) {
for (let div of this.elementMap[el]) {
// Add some text to give div a non-zero height.
const innerText = div.innerText;
div.innerText = 'XXX';
let divHeight = div.clientHeight;
div.innerText = innerText;
if (divHeight <= containerHeight)
continue;
// Update position
div.style.position = 'relative';
div.style.top = defaultAsPx((containerHeight - divHeight) / 2.0);
}
}
this.update(resetLine);
}
update(e) {
// 36|2020-09-14T20:37:53.2140000-05:00|3CA0|3|hash
const [logCode, logTimeStamp, hexValue, maxBars] = e.line;
if (logCode !== lbLogCode)
return;
// Process log line
this.limitBreakHistory.updateHistory(hexValue, maxBars);
// Update current LB
const currentLBKey = 'CurrentLB';
const formattedCurrentLB = formatNumber(this.limitBreakHistory.getCurrentValue(), this.options.numberFormat, currentLBKey);
this.setValue(currentLBKey, formattedCurrentLB);
// Update time until next bar
this.setValue('TimeToBar', this.limitBreakHistory.toTimeFormat(this.limitBreakHistory.secondsUntilNextBar()));
// Update time until max
this.setValue('TimeToMax', this.limitBreakHistory.toTimeFormat(this.limitBreakHistory.secondsUntilMax()));
// Update counts
this.setValue('LBCounts', `${this.limitBreakHistory.unknownCnt} / ${this.limitBreakHistory.surviveLethalCnt} / ${this.limitBreakHistory.passiveCnt}`);
this.setValue('PassiveTicks', this.limitBreakHistory.passiveCnt);
this.setValue('SurviveLethals', this.limitBreakHistory.surviveLethalCnt);
this.setValue('UnknownSource', this.limitBreakHistory.unknownCnt);
}
updateParty(party) {
// Updates the job duplicate counter
let jobDuplicates = 0;
const jobMap = {};
const roleMap = {};
const partyList = party.filter(member => member.inParty);
partyList.forEach(member => {
if (jobMap[member.job])
jobDuplicates++;
jobMap[member.job] = true;
let role = jobToRoleMap[kJobEnumToName[member.job]];
if (roleMap[role])
roleMap[role]++;
else
roleMap[role] = 1;
});
if (this.limitBreakHistory.bars === 3 && (roleMap['dps'] !== 4 || roleMap['tank'] !== 2 || roleMap['healer'] !== 2))
jobDuplicates++;
this.limitBreakHistory.party.list = partyList;
this.limitBreakHistory.party.jobDuplicates = jobDuplicates;
}
setValue(name, value) {
let nodes = this.elementMap[name];
if (!nodes)
return;
for (let node of nodes)
node.innerText = value;
}
}
class SettingsUI {
constructor(configStructure, savedConfig, settingsDiv, rebuildFunc) {
this.savedConfig = savedConfig || {};
this.div = settingsDiv;
this.rebuildFunc = rebuildFunc;
this.buildUI(settingsDiv, configStructure, savedConfig);
rebuildFunc(savedConfig);
}
// Top level UI builder, builds everything.
buildUI(container, configStructure, savedConfig) {
container.appendChild(this.buildHeader());
container.appendChild(this.buildAltHeader('(🔒lock overlay to hide settings)', 'settings-helptext'));
for (const opt of configStructure) {
if (opt.headerBefore)
container.appendChild(this.buildAltHeader(opt.headerBefore));
let buildFunc = {
checkbox: this.buildCheckbox,
select: this.buildSelect,
text: this.buildText,
}[opt.type];
if (!buildFunc) {
console.error('unknown type: ' + JSON.stringify(opt));
continue;
}
buildFunc.bind(this)(container, opt);
}
}
buildHeader() {
let div = document.createElement('div');
div.innerHTML = 'Limit Break Settings';
div.classList.add('settings-title');
return div;
}
buildAltHeader(label, className) {
let div = document.createElement('div');
div.innerHTML = label;
div.classList.add(className ? className : 'settings-altheader');
return div;
}
// Code after this point in this class is largely cribbed from cactbot's
// ui/config/config.js CactbotConfigurator.
// If this gets used again, maybe it should be abstracted.
async saveConfigData() {
await callOverlayHandler({
call: 'saveData',
key: overlaySettingsKey,
data: this.savedConfig,
});
this.rebuildFunc(this.savedConfig);
}
// takes variable args, with the last value being the default value if
// any key is missing.
// e.g. (foo, bar, baz, 5) with {foo: { bar: { baz: 3 } } } will return
// the value 3. Requires at least two args.
getOption() {
let num = arguments.length;
if (num < 2) {
console.error('getOption requires at least two args');
return;
}
let defaultValue = arguments[num - 1];
let objOrValue = this.savedConfig;
for (let i = 0; i < num - 1; ++i) {
objOrValue = objOrValue[arguments[i]];
if (typeof objOrValue === 'undefined')
return defaultValue;
}
return objOrValue;
}
// takes variable args, with the last value being the 'value' to set it to
// e.g. (foo, bar, baz, 3) will set {foo: { bar: { baz: 3 } } }.
// requires at least two args.
setOption() {
let num = arguments.length;
if (num < 2) {
console.error('setOption requires at least two args');
return;
}
// Set keys and create default {} if it doesn't exist.
let obj = this.savedConfig;
for (let i = 0; i < num - 2; ++i) {
let arg = arguments[i];
obj[arg] = obj[arg] || {};
obj = obj[arg];
}
// Set the last key to have the final argument's value.
obj[arguments[num - 2]] = arguments[num - 1];
this.saveConfigData();
}
buildNameDiv(opt) {
let div = document.createElement('div');
div.innerHTML = opt.name;
div.classList.add('option-name');
return div;
}
buildCheckbox(parent, opt) {
let div = document.createElement('div');
div.classList.add('option-input-container');
let input = document.createElement('input');
div.appendChild(input);
input.type = 'checkbox';
input.checked = this.getOption(opt.id, opt.default);
input.onchange = () => this.setOption(opt.id, input.checked);
parent.appendChild(this.buildNameDiv(opt));
parent.appendChild(div);
}
// <select> inputs don't work in overlays, so make a fake one.
buildSelect(parent, opt) {
let div = document.createElement('div');
div.classList.add('option-input-container');
div.classList.add('select-container');
// Build the real select so we have a real input element.
let input = document.createElement('select');
input.classList.add('hidden');
div.appendChild(input);
const defaultValue = this.getOption(opt.id, opt.default);
input.onchange = () => this.setOption(opt.id, input.value);
for (const [key, value] of Object.entries(opt.options)) {
let elem = document.createElement('option');
elem.value = value;
elem.innerHTML = key;
if (value == defaultValue)
elem.selected = true;
input.appendChild(elem);
}
parent.appendChild(this.buildNameDiv(opt));
parent.appendChild(div);
// Now build the fake select.
let selectedDiv = document.createElement('div');
selectedDiv.classList.add('select-active');
selectedDiv.innerHTML = input.options[input.selectedIndex].innerHTML;
div.appendChild(selectedDiv);
let items = document.createElement('div');
items.classList.add('select-items', 'hidden');
div.appendChild(items);
selectedDiv.addEventListener('click', (e) => {
items.classList.toggle('hidden');
});
// Popout list of options.
for (let idx = 0; idx < input.options.length; ++idx) {
let optionElem = input.options[idx];
let item = document.createElement('div');
item.classList.add('select-item');
item.innerHTML = optionElem.innerHTML;
items.appendChild(item);
item.addEventListener('click', (e) => {
input.selectedIndex = idx;
input.onchange();
selectedDiv.innerHTML = item.innerHTML;
items.classList.toggle('hidden');
selectedDiv.classList.toggle('select-arrow-active');
});
}
}
buildText(parent, opt) {
let div = document.createElement('div');
div.classList.add('option-input-container');
let input = document.createElement('input');
div.appendChild(input);
input.type = 'text';
input.value = this.getOption(opt.id, opt.default);
let setFunc = () => this.setOption(opt.id, input.value);
input.onchange = setFunc;
input.oninput = setFunc;
parent.appendChild(this.buildNameDiv(opt));
parent.appendChild(div);
}
}
function updateOverlayState(e) {
let settingsContainer = document.getElementById('settings-container');
if (!settingsContainer)
return;
const locked = e.detail.isLocked;
if (locked) {
settingsContainer.classList.add('hidden');
document.body.classList.remove('resize-background');
} else {
settingsContainer.classList.remove('hidden');
document.body.classList.add('resize-background');
}
OverlayPluginApi.setAcceptFocus(!locked);
}
// This event comes early and doesn't depend on any other state.
// So, add the listener before DOMContentLoaded.
document.addEventListener('onOverlayStateUpdate', updateOverlayState);
window.addEventListener('DOMContentLoaded', async (e) => {
// Get the container for the bar
let containerDiv = document.getElementById('container-limitbreak');
if (!containerDiv) {
console.error('Missing container');
return;
}
// Set option defaults from config.
let options = {};
for (const opt of configStructure)
options[opt.id] = opt.default;
// Overwrite options from loaded values.
const loadResult = await window.callOverlayHandler({ call: 'loadData', key: overlaySettingsKey });
if (loadResult && loadResult.data)
options = Object.assign(options, loadResult.data);
// Creating settings will build the initial bars UI.
// Changes to settings rebuild the bars.
let barUI;
let settingsDiv = document.getElementById('settings');
let buildFunc = (options) => {
while (containerDiv.lastChild)
containerDiv.removeChild(containerDiv.lastChild);
barUI = new BarUI(options, containerDiv);
};
let gSettingsUI = new SettingsUI(configStructure, options, settingsDiv, buildFunc);
window.addOverlayListener('LogLine', (e) => barUI.update(e));
window.addOverlayListener('PartyChanged', (e) => barUI.updateParty(e.party));
document.addEventListener('onExampleShowcase', () => barUI.update(resetLine));
window.startOverlayEvents();
});